I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. Could anybody give me any reason?
void memory(int *
Because you're wanting to get a pointer value back from the operations done in the function. malloc
allocates 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.
Main Function malloc
p p allocated
+---+ +---+
| 0 | | 0 | A
+---+ +---+
becomes...
p p allocated
+---+ +---+
| 0 | | ------------> A
+---+ +---+
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 malloc
back to the main program for use.
Main Function malloc
p p allocated
+---+ +---+
| 0 |<------- | A
| | | |
+---+ +---+
becomes...
p p allocated
+---+ +---+
| |<------- |
| ----------------------> A
+---+ +---+
and thus when main reads p, it gets A.