c - Array inside struct filled with garbage after initialization -



c - Array inside struct filled with garbage after initialization -

i defined info construction (foo) contains array of 25 pointers (members) itself. want initialize each of pointers null, init function isn't working correctly. when foo f returns foo_init(), of members null, others populated random values.

//in foo.h #include <stdio.h> #include <stdlib.h> typedef struct foo { struct foo * members[25] ; } foo ; void foo_init(foo * f) ; //in foo.c void foo_init(foo * f) { f = (foo*)malloc(sizeof(foo)); (size_t = 0 ; < 25 ; i++) { f->members[i] = null ; } /* ok here, members null */ } //in main.c #include "foo.h" int main(int argc, const char * argv[]) { foo f ; foo_init(&f) ; /* why isn't every index of f.members null? */ /* ... */ homecoming 0; }

i ran code through lldb. within foo_init(), members null. after returning foo_init(), f.members total of random garbage values.

the address of foo in main overwritten phone call malloc. remove line , initialization should work.

if want foo_init allocate memory can convert :

void foo_init(foo **out_f) { foo *f = malloc(sizeof *f); (size_t = 0 ; < 25 ; i++) { f->members[i] = null; } *out_f = f; }

or return pointer idiomatic in c :

foo *foo_init(void);

c arrays pointers initialization

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -