The short answer is that p
and q
are independent variables. So first p
will be assigned the same value as q
and then p
gets a new value due to the malloc
. q
is not changed by the function call. However, there is a memory leak due to p
(and q
) not being freed.
You can see this using a few prints.
#include <stdio.h>
#include <stdlib.h>
void f(int p[])
{
printf("--------------------\n");
printf("p is now %p\n", (void*)p);
printf("p points to the value %d\n", p[0]);
p = (int*)malloc(sizeof(int));
*p = 0;
printf("--------------------\n");
printf("p is now %p\n", (void*)p);
printf("p points to the value %d\n", p[0]);
printf("--------------------\n");
}
int main(){
int *q = 0;
q = (int*)malloc(sizeof(int));
*q = 1;
printf("q is now %p\n", (void*)q);
printf("q points to the value %d\n", q[0]);
f(q);
printf("q is now %p\n", (void*)q);
printf("q points to the value %d\n", q[0]);
return 0;
}
The output (with a few comments to explain):
q is now 0x1912010 // In main q is initialized
q points to the value 1 // In main the location q points to is initialized
--------------------
p is now 0x1912010 // In function p first has the same value as q
p points to the value 1 // so it also points to the same as q
--------------------
p is now 0x1913040 // In function p gets a new value due to malloc
p points to the value 0 // and the pointed to memory gets a new value
--------------------
q is now 0x1912010 // Back in main q is the same as before the function call
q points to the value 1 // and the pointed to memory is unchanged as well