20 July 2010

Some notes on pointers in C

Note the following simple program and Its output on GCC 3.2.3:


#include
#include

int main(void)
{
int *p;
printf("%p %i\n",p, *p);

int *p2 = malloc(sizeof(*p2));
printf("%p %i\n",p2, *p2);

int *p3 = NULL;
printf("%p \n",p3);

p3 = malloc(sizeof(*p3));
printf("%p %i\n",p3, *p3);
return 0;
}


The output is:

0x8048414 1474660693
0x8d3d008 0
(nil)
0x8d3d018 0


So, when you declare a pointer, it points to some garbage data.
When you malloc memory, the pointer points to some memory-allocated location.
When you assign NULL to a pointer, it becomes NULL Pointer and its address is NULL, and you need to reallocate memory for before use.

So,
Post a Comment