I was thinking about pointer initialization and tried the following two cases:
#include <stdio.h>
int main(int argc, char **argv)
{
int *d;
int f;
int p;
*d = 6;
printf("%d %d %d\n", *d, f, p);
return 0;
}
This code segfaults at the line (seen in gdb):
*d = 6;
Which makes sense because I am trying store a value at a random address.
I then tried the following:
#include <stdio.h>
int main(int argc, char **argv)
{
int *d;
int f = 10;
int p = 9;
*d = 6;
printf("%d %d %d\n", *d, f, p);
return 0;
}
This runs to completion with the output:
6 10 9
If only f
is initialized to 10 (p
is not initialized) or vice versa, the program still completes with output
6 10 0
or
6 0 9
(p
initialized). I do not understand why this works. My initial guess is that the initialization of either f
or p
makes space or orients memory to allow for the safe initialization of d
. I also thought about stack allocations, but am still unsure.