-3

How are pointers in C initialized? It seems like previous declarations change how they are initialized.

Consider the following example:

int *a;
printf("a: %p\n", (void*)a);

This code snippet results in

a: (nil)

So one could think that variables at function start are initialized with null, but if I execute this code:

int *a;
for(int i = 0; i < 1; i++){
    int *b;
    printf("a: %p\n", (void*)a);
    printf("b: %p", (void*)b);
}

This is the result:

a: 0x7ffff3bb2e40
b: (nil)

How can I determine how the variables are initialized?

M.M
  • 138,810
  • 21
  • 208
  • 365
NightRain23
  • 143
  • 1
  • 5

3 Answers3

1

Given that you are not assigning an initial value, it depends on what there is on the memory beforehand. So there are two possibilities

  • Garbage. Indeterminate values which come from a previous execution or status, etc...this l yields an undefined behaviour.
  • Initialization during startup. It is quite common to initialize to zero some segments of memory such us the bss segment during the startup (before main()). In this case, you are not initializating the variable, you are initializating the bunch of memory in which the variable is allocated, anyway, this won't yield an undefined behaviour.

Edited for accuracy due to M.M 's comment.

Jose
  • 3,306
  • 1
  • 17
  • 22
1

If a pointer is defined at file scope, it is initialized to NULL.

If it is defined at block scope, the pointer is uninitialized, so it could have any random value, including NULL.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 5
    uninitialized variables have *indeterminate value*, not any random value. The value could appear to change by itself between inspections, compare unequal with itself, and so on. – M.M Nov 22 '18 at 21:38
0

How are pointers in C initialized?

In C, local pointers (in automatic variables) are not initialized unless you code explicitly their initialization. You have an undefined behavior. Be scared.

The only pointers which are implicitly initialized are those in global or static variables (so called file scope variables). In practice, such pointers are initialized to all zero bits, which usually means the NULL pointer.

In practice, with a modern compiler like a recent GCC, you should enable all warnings and debug info (e.g. compile with gcc -Wall -Wextra -g). Then you'll get warnings. Improve your code to have none.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547