I defined a data structure (Foo) that contains an array of 25 pointers (members) to itself. I want to initialize each of those pointers to NULL, but my init function isn't working correctly. When my Foo f returns from foo_init(), only some of the members are NULL, others are just populated with 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));
for (size_t i = 0 ; i < 25 ; i++) {
f->members[i] = NULL ;
}
/* Ok here, all members are 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? */
/* ... */
return 0;
}
I ran my code through LLDB. Inside foo_init(), all members are NULL. But after returning from foo_init(), f.members is full of random garbage values.
mallocinto your class object?foo_init. Get rid of that line.