c++ - Structure having an array of pointers in c -
i implementing multibit trie in c. getting segmentation fault error. when run program. don't know going wrong?
the node of multi bit trie that:
struct mtnode{ /* nodes array 8 elements. each element pointer child node.*/ mtnode* nodes[8]; // 2^stride = 2^3 = 8 int nexthop; };
each node initialized following:
typedef mtnode node; node *init_mtnode(){ node *ret = (node*) malloc(sizeof(node)); int size = (int)pow(2,stride); (int i=0; i<size ; ++i) { ret->nodes[i] = null; } ret->nexthop = -1; return ret; }
is wrong in init_mtnode method?
there multiple possible reasons:
you don't check
malloc()
null
, unlikenew
throw exception,malloc()
returnnull
if error happens.you calculate value of
size
, loopsize
times, array can hold8
pointers.
try this
typedef mtnode node; node *init_mtnode() { node *ret; int size; ret = static_cast<node *>(malloc(sizeof(node))); if (ret == null) /* check null */ return null; size = 2 << stride; if (size >= 8) size = 7; /* maximum possible value */ (int = 0 ; < size ; ++i) ret->nodes[i] = null; ret->nexthop = -1; return ret; }
Comments
Post a Comment