C语言 双自由或腐败(fasttop)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20019512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
double free or corruption (fasttop)
提问by Thair Abdalla
The following section of my code gives me this messege when executing * glibc detected ./a.out: double free or corruption (fasttop): 0x08e065d0 **
我的代码的以下部分在执行* glibc detected时给了我这个消息./a.out:双重释放或损坏(fasttop):0x08e065d0 **
i have gone through the code many times but i cant clealry see how i am misusing the free (temp2)
我已经多次阅读代码,但我无法清楚地看到我是如何滥用 free (temp2)
bool found= false;
int x=0;
for ( x=0; x<=312500; x++)
{
while (count <=32)
{
fscanf (file, "%d", &temp->num);
temp->ptr=NULL;
newNode = (NODE *)malloc(sizeof(NODE));
newNode->num=temp->num;
newNode->ptr=NULL;
if (first != NULL)
{
temp2=(NODE *)malloc(sizeof(NODE));
temp2=first;
while (temp2 != NULL && !found)
{
if (temp2->num == newNode->num)
{found=true;}
temp2= temp2->ptr;
}
free(temp2);
if (!found)
{
last->ptr=newNode;
last=newNode;
count=count+1;
}
}
else
{
first = newNode;
last = newNode;
count=count+1;
}
fflush(stdin);
}
回答by Paul92
The problem is here:
问题在这里:
temp2=first;
Basically, when you free temp2, you free first, not the memory allocated here:
基本上,当你释放 temp2 时,你首先释放,而不是这里分配的内存:
temp2=(NODE *)malloc(sizeof(NODE));
, which remains a memory leak, because after the assignment it can't be freed anymore.
,这仍然是内存泄漏,因为在分配之后它不能再被释放。
Also, your code has probably some more problems (one is that you shouldn't use fflushon an input stream), but without some more details, it's impossible to tell.
此外,您的代码可能还有更多问题(一个是您不应该fflush在输入流上使用),但如果没有更多详细信息,则无法判断。

