c - Memory allocation of fixed size array inside a struct -
i have following tree node struct holds pointers other tree nodes:
struct node { // ... struct node* children[20]; }
the idea want check whether there node*
inside children
, based , go deeper tree. when allocate node
want have children
20 null
values. not doin
- how should allocate array in order not errors
conditional jump or move depends on uninitialised value(s)
(valgrind)? - would better use
struct node** children
, allocate fixed size each time allocate new node?
edit: example of 1 place valgrind complains:
for(int i=0;i<20;i++) if(node->children[i] != null) do_something_with_the_node(node->children[i]);
when allocate new instance of struct node
, must set contained pointers null
mark them "not pointing anywhere". make valgrind warning go away, since pointers no longer uninitialized.
something this:
struct node * node_new(void) { struct node *n = malloc(sizeof *n); if(n != null) { for(size_t = 0; < sizeof n->children / sizeof *n->children; ++i) n->children[i] = null; } return n; }
you cannot portably use either memset()
on n->children
nor calloc()
, since give "all bits zero" not same "pointer null
".