Question

I am creating a binary tree as small project to learn C. Here is all the code you need.

typedef struct {
  int value;
  struct Node *leftchild;
  struct Node *rightchild;
  struct Node *parent;
} Node;

typedef struct {
  Node *root;
} BinaryTree;

void newBT( BinaryTree *_bt ) {
  _bt->root = 0;
  return;
};

Node* makeNode(int _value ) {
  Node *node;
  node->value = _value;
  node->leftchild = 0;
  node->rightchild = 0;
  node->parent = 0;
  return node;
};

void insert( BinaryTree* _bt, int _value ) {
  _bt->root = makeNode(_value);
  return;
};

Now, I have tested my makeNode() function and it works as intended and I checked it using a has() function which traverses the list and returns true if it finds a node with the given value, returns false otherwise. It is the first commented out line in main() below. When I pass my BinaryTree into insert() and declare the same line using a pointer I get a Bus error:10.

int main () {
  BinaryTree bt;
  newBT(&bt);
  //bt.root = makeNode(14);
  insert(&bt, 14);
  //printf("%d \n", has(&bt, 14));
  return 0;
}

Any suggestions?

Was it helpful?

Solution

makeNode is writing to the (undefined) address pointed to by an uninitialised pointer. You don't own the memory this points to so attempting to write to it results in undefined behaviour; a crash is a valid (and often useful) example of undefined behaviour.

You need to allocate memory here

Node* makeNode(int _value ) {
    Node *node = malloc(sizeof(*node));
    if (node == NULL) {
        return NULL;
    }
    ...

Make sure to return this memory to the system - by calling free(node) - when you remove a node from your list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top