0

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
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
spaul
  • 13
  • 2
  • 10
    `&x` gives you the address of the pointer, not the memory address where it points to. – mch Sep 24 '18 at 13:39
  • Moreover, it doesn't have to be in different place... – Eugene Sh. Sep 24 '18 at 13:41
  • wow what a brain fart. thank you!!!! – spaul Sep 24 '18 at 13:47
  • In C, allocated memory needs to be freed at the end. If you overwrite the original `x`, the original memory will be still allocated but lost forever. Take a look to `realloc()`, too. Moreover, [do not cast the result of malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Giovanni Cerretani Sep 24 '18 at 13:56
  • OT: note that you have a memory leak when you assign to `x` the second time. BTW: You don't need to cast the return value from `malloc` – Support Ukraine Sep 24 '18 at 15:01

1 Answers1

3
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)
Rizwan
  • 3,324
  • 3
  • 17
  • 38