c - Variable initialization and pointer segfault -
i thinking pointer initialization , tried following 2 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 @ line (seen in gdb):
*d = 6;
which makes sense because trying store value @ random address.
i tried 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 completion output:
6 10 9
if f
initialized 10 (p
not initialized) or vice versa, program still completes output
6 10 0
or
6 0 9
(p
initialized). not understand why works. initial guess initialization of either f
or p
makes space or orients memory allow safe initialization of d
. thought stack allocations, still unsure.
your first problem in *d = 6;
you're trying to dereference invalid pointer.
d
not initialized (allocated memory) , points invalid memory location. attempt dereference lead undefined behavior.
fwiw, second code produces ub same reason.
additionally, in first code snippet, writing
printf("%d %d %d\n", *d, f, p);
where f
, p
uninitialized automatic local variable, you're trying read indeterminate values, again, produces ub. avoided in second snippet explicit initialization.
Comments
Post a Comment