Reputation: 13
It is my understanding that you can reallocate a heap using the same variable name and it will allocate memory in a different location in space.
However, in this example, I am getting the same memory address in my second malloc for the pointer variable x. Any ideas?
void main()
{
int *x = (int*)malloc(sizeof(int)); //allocate space for int value
*x = 100; //dereference x for value
printf("The value of x is %i address is %p\n",*x, &x);
int *y = (int*)malloc(sizeof(int)); //allocate space for int value
*y = 150; //dereference x for value
printf("The value of y is %i address is %p\n",*y, &y);
x = (int*)malloc(sizeof(int)); //allocate space for int value
*x = 400; //dereference x for value
printf("The value of x is %i address is %p\n",*x, &x);
}
gcc gives me this:
The value of x is 100 address is 0xffffcc08
The value of y is 150 address is 0xffffcc00
The value of x is 400 address is 0xffffcc08
Upvotes: 0
Views: 431
Reputation: 3696
printf("The value of x is %i address is %p\n",*x, &x);
&x
here it gives the address of the variable x and not what it is pointing to. To get the address of where it is pointing to use following :
printf("The value of x is %i address is %p\n",*x, (void *)x)
Upvotes: 3