1

I'm trying to write a Binary Search Tree in C, but I keep getting this strange error. First of all, I'm not free'ing anything. The error I'm getting is:

malloc: *** error for object 0x7fb4794025e8: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug

I realized it was in the insert(NODE * ROOT, int data, char * text) method because it was seg faulting and giving me that error right when I allocated temp->left. I'm not sure why this is happening, I tried looking online and had no luck.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Create a Struct Node.
typedef struct node
{
  int data;
  char text[20];
  struct node * left;
  struct node * right;
} NODE;

// Check if the root is empty
int isEmpty(NODE * root) {
  if(root == NULL)
    return 0;
  return 1;
}

void insert(NODE * ROOT, int data, char * text) {
  NODE * temp = ROOT;
  if(data < temp->data) {
    if(temp->left != NULL) {
      insert(temp->left, data, text);
    } else { // If temp's left is indeed NULL, then we can insert to the left of the node.
      temp->left = malloc(sizeof(NODE*));
      temp->left->data = data;
      strcpy(temp->left->text, text);
      temp->left->left = NULL;
      temp->left->right = NULL;
    }
  }
}

void insertToTree(NODE ** ROOT, int data, char * text) {
  if(isEmpty(*ROOT) == 0) {
    // The root is empty, so let's append data to it.
    *ROOT = malloc(sizeof(NODE*));
    (*ROOT)->left = NULL;
    (*ROOT)->right = NULL;
    (*ROOT)->data = data;
    strcpy((*ROOT)->text, text);
  } else {
    insert(*ROOT, data, text);
  }
}

int main() { 
  NODE * root = NULL;
  insertToTree(&root, 5, "Jack");
  insertToTree(&root, 4, "Max");
  printf("%s %d\n", root->text, root->data);
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Stuy
  • 105
  • 3
  • 10

1 Answers1

1

Your malloc is not quite correct.

sizeof( NODE*) is not equal to sizeof( NODE )

so when you do a malloc

temp->left = malloc(sizeof(NODE*));

or

*ROOT = malloc(sizeof(NODE*));

you are essentially allocation less number of bytes than you need.

chage to

malloc(sizeof(NODE*));

Tip - use gdb, valgrind to identify invalid reads/ writes etc

asio_guy
  • 3,667
  • 2
  • 19
  • 35