C:free():下一个大小无效(快)

时间:2013-10-06 23:18:50

标签: c

您好我花了最近几个小时查看此代码,以找出导致此内存错误的原因。我一再被告知,这是一种解放从未被摩擦过的东西或两次释放东西的情况,但我已经完成并缩减了代码,以确保这些都不可能。整个项目是一个链表,但我已经取出了项目的大部分组件,以尽可能小地复制错误。谢谢! 守则:

#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 ***

1 个答案:

答案 0 :(得分:7)

更改

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

感谢您尽力做出最小的测试用例。