【发布时间】:2015-06-05 12:53:59
【问题描述】:
我正在从一个文件中读取(每行包含 1 个单词)并将每一行放入一个数组中。它在即将关闭文件时崩溃(* glibc检测到* proj:损坏的双链表:0x0000000002139240 ***)。除了第一个元素之外的所有内容都被正确复制(第一个元素应该是“你好吗”,但实际上是“0”)。非常感谢您对此提供任何帮助。
int i = -1;
int numb;
int wsize;
while (fgets(word,30,file)!=NULL)
{
if (i==-1)
{
if(word[strlen(word)-1]=='\n')
{
word[strlen(word)-1] = 0;
}
numb = atoi(word);
ptr = malloc(sizeof(char*)*numb);
}
else
{
if(word[strlen(word)-1]=='\n')
{
word[strlen(word)-1] = 0;
}
wsize = strlen(word);
ptr[i] = malloc(sizeof(char*)*wsize);
strncpy(ptr[i],word,strlen(word));
size++;
}
i++;
}
int j=0;
while(j<16) //prints to see if they were copied corectly
{ //ptr[0] was the only one that did not copy corectly
printf("%s\n",ptr[j]);
j++;
}
fclose(file);
printf("test\n"); //was never printed so I assume it crashes at fclose()
return 1;
【问题讨论】:
-
在退出程序之前,代码需要释放所有那些 malloc 的区域。否则会产生一系列内存泄漏。虽然程序的退出将(可悲地)释放所有分配的内存,但最好在其自身之后进行代码清理,特别是当程序变得更大、运行时间更长并且有越来越多的分配内存要释放时跨度>