I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. What is the reason?
void memory(int * p, int size) {
try {
p = (int *) malloc(size*sizeof(int));
} catch(exception& e) {
cout << e.what() << endl;
}
}
It does not work in the main function as below:
int *p = 0;
memory(p, 10);
for(int i = 0; i < 10; i++)
p[i] = i;
However, it works like thi .
void memory(int ** p, int size) { `//pointer to pointer`
try {
*p = (int *) malloc(size*sizeof(int));
} catch(exception& e) {
cout<<e.what()<<endl;
}
}
int main()
{
int *p = 0;
memory(&p, 10); // Get the address of the pointer
for(int i = 0; i < 10; i++)
p[i] = i;
for(int i = 0; i < 10; i++)
cout << *(p+i) << " ";
return 0;
}
Because you’re wanting to get a pointer value back from the operations done in the function.
mallocallocates memory and gives you an address for that memory.In your first example, you store that address in the local argument variable
p, but since it’s just the argument, that doesn’t make it back to the main program, because C/C++ are pass-by-value by default – even for pointers.and thus when main reads p, it gets 0, not A.
In your working code, you follow the pointer passed to an address, and that address gives you the location of the pointer variable in the main program. You update the pointer value at that address, which the main program can then look up the value of to use as its memory location – thus passing the address returned by
mallocback to the main program for use.and thus when main reads p, it gets A.