简体   繁体   中英

Why doesn't malloc work in my own implementation of BST tree

This is the node definition:

typedef struct drzewo BST;
struct drzewo  {
   int key;
   BST *left;
   BST *right;
   BST *p;
};

and I am trying to write add function:

BST *add(  BST *root, int val)
{
   BST  *x = root;
   BST *nowe =(BST*)malloc(sizeof(BST));


   nowe->key = val;
   nowe->left=nowe->right=nowe->p=NULL;
   ...
}

but it appears that malloc is resulting in segmentation fault, when root=NULL, or other error (writing on windows). Why is that so?

I suspect that, within the ... you have an assignment to (or read from) x->left or x->right , to facilitate linking your newly-allocated node into the tree. If root is NULL, this should fail.

Use valgrind (if your system is Linux) or a debugger to debug your issues.

Learn to use a debugger (eg gdb on Linux).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM