1

您好,我在过去的几个小时里一直在查看此代码,试图找出导致此内存错误的原因。我一再被告知这是一种释放从未分配过的东西或释放两次的情况,但我已经完成并缩小了代码以确保这些都不可能。整个项目是一个链表,但是我把项目的大部分组件都去掉了,以尽量减少错误的复制。谢谢!编码:

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

struct lnode{
  int count;
  int line;
  struct lnode *next;
  char *word;
}; 

struct lnode* newNode (char* word, int line) {
  struct lnode *myNode = malloc(sizeof(struct  lnode*));

  myNode->word = (char*)malloc((strlen(word))*sizeof(char));
  strcpy(myNode->word,word);
  myNode->count = 1;
  myNode->line = line;
  myNode->next = NULL;
  return myNode;
}
void freeNode(struct lnode * myNode){
  //free(myNode->word);
  //myNode->word = NULL;
  free(myNode);
  myNode = NULL;
}
int main(){
  struct lnode *n = newNode("Test", 2);
  free(n);
  return 0;
}

给出这个错误:

*** glibc detected *** ./listTest: free(): invalid next size (fast): 0x085d008 ***
4

1 回答 1

9

改变

  struct lnode *myNode = malloc(sizeof(struct  lnode*));

  struct lnode *myNode = malloc(sizeof(struct  lnode));

  myNode->word = (char*)malloc((strlen(word))*sizeof(char));

  myNode->word = (char*)malloc((strlen(word)+1)*sizeof(char));

感谢您努力制作最小的测试用例。

于 2013-10-06T23:22:05.047 回答