malloc:***对象的错误:释放的对象

时间:2017-11-20 05:15:28

标签: c memory binary-search-tree free

我正在尝试用C编写二进制搜索树,但我一直收到这个奇怪的错误。首先,我没有任何自由。我得到的错误是:

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

我意识到它是在插入(NODE * ROOT,int data,char * text)方法中,因为它是seg faulting并且在我分配temp-> left时给出了我的错误。我不确定为什么会发生这种情况,我试着在网上寻找并且没有运气。

#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);
}

1 个答案:

答案 0 :(得分:1)

你的malloc不太正确。

  

sizeof(NODE *)不等于sizeof(NODE)

所以当你做一个malloc

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

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

您实际上是分配的字节数少于您需要的字节数。

chage to

malloc(sizeof(NODE*));

提示 - 使用gdb,valgrind识别无效的读/写等