c - allocating null pointer when passed to function -
this program contains typical node struct linked list (so pointer next node , int containing value). have following test functions:
void f(node** y, int value) { node* x = *y; if(!x) { printf("case1...\n"); x = (node*)malloc(sizeof(node)); x->data = value; return; } printf("case2...\n"); x->next = (node*)malloc(sizeof(node)); x->next->data = value; return; } void myprint(node** y) { node* x = *y; printf("printing...\n"); printf("%d %d\n", x->data, x->next->data); return; } int main() { node* n = null; f(&n, 5); f(&n, 10); myprint(&n); }
this code produces following output in linux:
case1... case1... printing... segmentation fault
i don't understand why passing null pointer function cause first case occur. seems pointer being passed value, don't think that's what's going on. if call malloc()
on node inside of main()
, pass f()
, second case hit never first. @ least makes partial sense me, since node never null when passed f()
main()
, allocating node before passing f()
means null check inside f()
never true.
is i'm trying possible? there way pass n
f()
while it's null , have behave way want to? or have allocate n
outside of f()
, remove null check inside of f()
?
after allocation x
need set in *y
in function f()
. otherwise, not reflected once f()
returns.
so change code to
void f(node** y, int value) { node* x = *y; if(!x) { printf("case1...\n"); x = (node*)malloc(sizeof(node)); x->data = value; *y = x; //set allocated pointer return; } printf("case2...\n"); x->next = (node*)malloc(sizeof(node)); x->next->data = value; return; }
Comments
Post a Comment