0

I recently finished "The C Programming Language - 2nd Edition" and I thought a good next step would be creating my own data structures library using C.

I'm currently working on implementing a standard binary tree and I've been stuck with the insertion method. So far I've created the node struct:

typedef struct node
{
    int data;
    struct node * rc;
    struct node * lc;
}NODE;

and I'm trying to get insertion method to work when presented with the root node of the tree. Here is how I've created the root node and how I call it in the addNode() function:

int main() {
    NODE * root = NULL;
    addNode(12, root);

    return 0;
}

My addNode() function is structued like so:

void addNode(int info, NODE * node)
{
    if (node == NULL) {
        node = (NODE *)malloc(sizeof(NODE));
        node->data = info;
        node->rc = NULL;
        node->lc = NULL;
    }
}

When I try to display the actual value of 'data' stored within the NODE * root from the main method, I get a segmentation fault. After some exploring, I realized that the reason for this was that my memory allocation for node in the addNode() method was not actually redefining root to be newly allocated memory with the value 'info' but was instead creating a separate NODE * node.

Ultimately I think my issue is that I'm still trying to grasp pointers in C but I would greatly appreciate any insight into how I could go about fixing my code. (Sorry in advance if my C terminology is not quite there yet either)

AC-5
  • 193
  • 1
  • 1
  • 10
  • 1
    `node = ...` within your function means *nothing* to the caller (in this case `main`). Pointers are passed by value in C, just like everything else. If you want to modify the pointer in `main()` you either have to pass it by address (of the pointer, so as a pointer-to-pointer) and dereference it accordingly in your function for assignment, or utilize the otherwise unused return result of `addNode`. This question appears near-daily here, so a duplicate should be forthcoming. [Like this one](https://stackoverflow.com/questions/13431108/changing-address-contained-by-pointer-using-function). – WhozCraig Aug 22 '18 at 21:18

1 Answers1

1

The problem is that in your addNode function you are actually modifying the local node, not the actual variable in the outer scope. To fix this issue, you need to pass a pointer to pointer to NODE in addNode. Also, please do not cast the result of malloc as it is not needed and it may hide bugs i.e. you might forget to add the needed headers.