c++ - malloc issue with struct of containing an array of strings -
i've read other posts issue. when change top line:
typedef char key_type;
to
typedef string key_type;
i memory access error @ p->key[1] = x;
typedef char key_type; // change string , breaks typedef struct node_tag{ int count; key_type key[maxsize + 1]; struct node_tag *branch[maxsize + 1]; }node_type; node_type *insert(key_type newkey, node_type *root) { key_type x; /* node reinserted new root */ node_type *xr; /* subtree on right of x */ node_type *p; /* pointer temporary use */ bool pushup; /* has height of tree increased? */ pushup = pushdown(newkey, root, &x, &xr); if (pushup) { /* tree grows in height.*/ /* make new root: */ p = (node_type *)malloc(sizeof(node_type)); p->count = 1; p->key[1] = x; // memory access error p->branch[0] = root; p->branch[1] = xr; return p; } return root; }
what small modification can made eliminate memory access error?
you didn't call constructor string. also, in habit of writing c++ , not c:
typedef string key_type; struct node_type{ // don't need typedef ... int count; key_type key[maxsize + 1]; node_type *branch[maxsize + 1]; }; node_type *insert(key_type newkey, node_type *root) { key_type x; /* node reinserted new root */ node_type *xr; /* subtree on right of x */ node_type *p; /* pointer temporary use */ bool pushup; /* has height of tree increased? */ pushup = pushdown(newkey, root, &x, &xr); if (pushup) { /* tree grows in height.*/ /* make new root: */ p = new node_type; p->count = 1; p->key[1] = x; // memory access error p->branch[0] = root; p->branch[1] = xr; return p; } return root; }
if don't provide ctor struct compiler create 1 (as dtor).