Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer default value .?

Tags:

c

pointers

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?

like image 969
Jeegar Patel Avatar asked Aug 30 '11 08:08

Jeegar Patel


People also ask

What is the default value of pointer variable in go?

Hence, the default value of a pointer is always nil. Here, in the line var ptr = new(int) , the variable ptr becomes a pointer of type int .

Is a pointer by default null?

N@G3 " [...] a variable or pointer is given a null "value" by default [...] " Pointers have no specific default value.

What is the value of the pointer?

A pointer is a variable that points to another variable. This means that a pointer holds the memory address of another variable. Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable.

Is static pointer initialized to null?

No, it will be initialized to the NULL pointer value, whether or not its representation is zero. For pointers, the constant 0 transforms to the NULL pointer value, not the bit pattern of all zeros.


1 Answers

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.

like image 70
Seth Carnegie Avatar answered Nov 16 '22 00:11

Seth Carnegie