I wrote the below program to set a value (here it's 3) to some location at memory that is pointed by a pointer named p using a function named f() and print it in the main:
#include <iostream>
using namespace std;
void f(float* q)
{
q=new float;
*q=3;
}
int main()
{
float *p= nullptr;
f(p);
cout<<*p;
return 0;
}
But when I want to compile it, I receive this compile time error :
ap1019#sharifvm:~$ g++ myt.cpp
myt.cpp: In function âint main()â:
myt.cpp:12:11: error: ânullptrâ was not declared in this scope
float *p=nullptr;
^
ap1019#sharifvm:~$
What's wrong?
It seems that pointer literal nullptr is not supported by your compiler.
You may use null pointer constant instead. For example
float *p = 0;
But in any case your program is wrong. It has a memory leak because you store the address of the allocated memory in a local variable of function f that will be destroyed after exiting the function.
The program could look the following way
#include <iostream>
using namespace std;
void f( float **q)
{
*q = new float;
**q = 3;
}
int main()
{
float *p = 0;
f( &p );
cout << *p;
delete p;
return 0;
}
Or you could use reference to the pointer. For example
#include <iostream>
using namespace std;
void f( float * &q)
{
q = new float;
*q = 3;
}
int main()
{
float *p = 0;
f( p );
cout << *p;
delete p;
return 0;
}
nullptr is only supported from gcc-4.6 or later.
You can easily workaround that with a const void *nullptr=(void*)0;, but to avoid later problems with a gcc upgrade, I suggest to
upgrade your gcc (4.6 is quite old)
or don't use it.
It is only syntactic sugar, you don't need that.
The word null is not reserved by the C++ standard.
Use NULL instead.
Related
I have a shared library mod.so and it has a function getptr to return pointer to a dynamically allocated memory.It also has a function Unload which frees the memory which was allocated.
The main program loads this shared library at runtime and gets the pointer from getptr
function but when Unload function is called it gives me Segmentation Fault.
main.cpp
#include <iostream>
#include <dlfcn.h>
using namespace std;
int main()
{
void* module = dlopen("mod.so",RTLD_LAZY);
typedef int*(*func)();
typedef void(*func1)();
func f = (func)dlsym(module,"getptr");
func1 b = (func1)dlsym(module,"Unload");
int* p = f();
b();
}
mod.cpp
#include <iostream>
#include <vector>
using namespace std;
vector<int*> allocated;
extern "C"
{
int* getptr()
{
int* p = new int;
*p = 1024;
allocated.push_back(p);
return p;
}
void Unload()
{
for(auto e: allocated)
delete e;
}
}
The mod.cpp is compiled as:
g++ -shared mod.cpp -o mod.so -fPIC
dlopen("mod.so",RTLD_LAZY) returns NULL. Try this:
void* module = dlopen("./mod.so",RTLD_LAZY);
if (!module) {
fprintf(stderr, "error in dlopen: %s\n", dlerror());
return 1;
}
Edit: with this modification your code worked for me on Linux/amd64 with gcc-10.2
Mind you, should you call Unload twice, it would cause serious problems. Possible fix:
#include <iostream>
#include <vector>
using namespace std;
vector<int*> *allocated= NULL;
extern "C"
{
int* getptr()
{
if (!allocated) allocated= new vector<int *>();
int* p = new int;
*p = 1024;
allocated->push_back(p);
return p;
}
void Unload()
{
if (allocated) {
for(auto e: *allocated)
delete e;
delete allocated;
allocated= NULL;
}
}
}
I am trying to define a type for function pointers, in c++. However, once I define the pointer funcp as a fptr, I cannot redefine the pointer as a different function, times. This program does not even compile. Is this because I have to delete the nullptr before reassigning times to funcp?
My code:
#include <iostream>
using namespace std;
typedef int (*fptr)(int, int);
int times(int x, int y)
{
return x*y;
}
fptr funcp = nullptr;
funcp = times;
int main()
{
return 0;
}
The problem is that you are trying to do that outside of any function. Try that:
int main()
{
funcp = times;
return 0;
}
Your question has nothing special for C++17. To make it a little more modern and easier to read you may use the using instead of typedef:
using fptr = int (*)(int, int);
I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
Voilà!
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.
#include <iostream>
#include <iterator>
using namespace std;
void print(int ia[])
{
int *p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
int main()
{
int ia[] = {1,2,3,4},i;
print(ia);
return 0;
}
P pointer to the first element in ia.
why it said"error: no matching function for call to 'begin(int*&)' c++"
thanks!:)
Because inside print(), the variable ia is a pointer, not an array. It doesn't make sense to call begin() on a pointer.
You are using the begin and end free functions on a pointer, that's not allowed.
You can do something similar with C++11's intializer_list
//g++ -std=c++0x test.cpp -o test
#include <iostream>
#include <iterator>
using namespace std;
void print(initializer_list<int> ia)
{
auto p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
int main()
{
print({1,2,3,4});
return 0;
}
As others pointed out, your array is decaying to a pointer. Decaying is historical artifact from C. To do what you want, pass array as reference and deduce array size:
template<size_t X>
void print(int (&ia)[X])
{
int *p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
print(ia);
I am getting the above error during compilation:
Structure:
struct connection_handlers
{
int m_fd;
}
struct connection_handlers ** _queue;
int main()
{
_queue = (struct connection_handlers **) malloc ( 3* sizeof ( struct connection_handlers *)); //Allocating space for 3 struct pointers
for (i=0;i<3;i++)
{
_queue[i]->m_fd=-1;
}//Initializing to -1
//.....
//I assign this varaible to the file descriptor returned by accept and then
//at some point of time i try to check the same variable and it gives compilatio error.
for (i=0;i<3;i++)
{
if (_queue[i]->m_fd!=-1)
}//It give error at this line.
}
What could be the reason for error.
Thanks
Since you tagged this question both C and C++, here is what is wrong with your C++.
don't put struct inside your casts
don't use implicit int for your loop counters
struct declarations need a terminating ;
_queue is declared with a messed-up type
your last loop is missing
Once you clean that up it compiles fine.
#include <cstdlib>
struct connection_handlers {
int m_fd;
};
int main() {
connection_handlers** _queue = (connection_handlers**) malloc(3*sizeof (connection_handlers*));
for (int i=0;i<3;i++) {
_queue[i]->m_fd=-1;
}
for (int i=0;i<3;i++) {
if (_queue[i]->m_fd!=-1)
; // DOES NOTHING
}
}
_queue[i] is a connection_handlers *. You can't compare that to -1, which is an int. Did you mean to check _queue[i]->m_fd?