18

Look,

  typedef struct jig 
   { 
         int *a;
         int *b;
   }temp;

now stage 1 :

temp *b;
b= (temp*)malloc(sizeof(temp));

if(b->a != NULL)
    printf("a is not null\n");
else
    printf("a is null\n");
if(b->b != NULL)
    printf("b is not null\n");
else
    printf("b is null\n");

output is :

a is null
b is null

now stage 2 :

temp b;

if(b.a != NULL)
    printf("a is not null\n");
else
    printf("a is null\n");
if(b.b != NULL)
    printf("b is not null\n");
else
    printf("b is null\n");

output is :

a is not null
b is not null

why this is happening?

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222

4 Answers4

48

Pointers have no default value. The value they have is just whatever junk was in the memory they're using now. Sometimes a specific compiler will zero out memory, but that's not standard so don't count on it.)

The memory from malloc being NULL was a coincidence; it could have been any other value just as easily. You need to and should always manually set all your pointers to NULL.

Another alternative is you can also use calloc, which does the same thing as malloc but sets all bits to 0 in the block of memory it gives you. This doesn't help with stack variables though, so you still have to set those to NULL by yourself.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
8

This is completely operating system dependent, there's no telling where pointers will be pointing in what case, since that isn't specified. You should always set your pointers to NULL no matter what.

Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43
3

Chance, that's what's happening. Nobody says uninitialized, non-static memory needs to hold any value. Both could contain anything.

  • In the first case it simply happened that malloc returned memory from an erased page (so it contains 0)
  • In the second case there was stuff on the stack so the memory contains garbage
cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

In both cases the contents of temp will be uninitialized (random) data. They can be null, or non-null. No matter how consistently you get the same values, don't rely on that unless the documentation specifically states what they must be.

hamstergene
  • 24,039
  • 5
  • 57
  • 72