arsonist_50 arsonist_50 - 3 months ago 8
C Question

Usage of %p for pointer to pointers

#include<stdio.h>
#include<stdlib.h>

void allocateMemory(int ** a)
{
a=malloc(sizeof(int *));
printf("\nInt ** %p\nInt * %p\nInt %p",a,&a,*a);
}

void main()
{
int *t;
allocateMemory(&t);
printf("\nInt * %p\nInt %p",&t,t);
}


My output for this code was

Int ** 0x124e010
Int * 0x7fffef9d1758
Int (nil)
Int * 0x7fffef9d1778
Int (nil)


When I used '&a' in the printf statement it should have printed the address of the pointer to pointer a. But it gave me the address of the pointer t, which I should have got when I used 'a'.

Can someone explain why my output the other way around?

Also the first address in the output is of only 6 digits compared to the 12 digit address, which one of them is the norm?

Answer

If I'm guessing your intentions right, this:

a=malloc(sizeof(int *));

Should be:

*a=malloc(sizeof(int *));

Otherwise you're just assigning to the local a (which will be thrown away) instead of storing to the int * pointed by a.

Also, in the output you posted, &a and &t are not the same (even though they're close). They can't be the same since a and t are different variables.

With the fix, you'll get the same output for a and &t, just like you expected (you were corrupting a).

About digits: for %p, C11 ยง7.21.6.1 8 says:

The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

So many possibilities exist. On many implementations it will print the hexadecimal address (16 digits for 64bit, 8 digits for 32bit). In your case, they appear shorter because the implementation omits leading zeroes and usually heap is at a lower memory location than stack.

Comments