0

I wrote a simple program in C (newbie in C)

when i try to compile this program it's get compiled.

created pointer to int 'p' and store the address of of variable 'a'

when i derefernce the pointer it show the value 0 but i never assigned any value

to my variable so where does 0 come from ? and if we write int a; it allocates space in the memory even before assigning any value to it.

#include <stdio.h>

int main()
{
    int a;
    int *p = &a;
    printf("%d\n", *p);
    return 0;
}

compiler : clang

2 Answers2

5

The value of an uninitialized variable is indeterminate. Reading from an uninitialized variable is undefined behaviour. So anything can happen. 0 is also a possible result of that.

C11 standard says:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

and

indeterminate value is defined as:

either an unspecified value or a trap representation

P.P
  • 117,907
  • 20
  • 175
  • 238
2

It doesn't come from anywhere! It's an arbitrary value.

You didn't initialise a, so what happens when you try to print its value is completely unpredictable.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055