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

  1. how should allocate array in order not errors conditional jump or move depends on uninitialised value(s) (valgrind)?
  2. 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".


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -