【发布时间】:2011-12-09 23:19:36
【问题描述】:
我正在尝试创建一个删除整个列表的函数,但我不断收到错误消息。 除了cleaner() 函数外,一切正常。
#include <stdio.h>
#include <stdlib.h>
struct node{
int n;
struct node *next;
};
typedef struct node NOD;
NOD *create_first_node(int i)
{
NOD *q;
q=(NOD*)malloc(sizeof(NOD*));
q->n=i;
q->next=NULL;
return q;
}
NOD * add_to(NOD *x)
{
NOD *q;
q=(NOD*)malloc(sizeof(NOD*));
q->n=rand();
x->next=q;
q->next=NULL;
return q;
}
void show_list(NOD *p)
{
printf("root");
while(p->next){
printf(" -> %d",p->n);
p=p->next;
}
printf("\n");
}
void cleaner(NOD *p)
{
NOD *r;
while(p)
{
r=p;
p=r->next;
free(r);
r=NULL;
}
}
int main()
{
int i;
NOD *root,*c,*r;
root=create_first_node(1);
c=r=root;
c=add_to(root);
for(i=0;i<10;i++)
{
r=c;
c=add_to(r);
}
show_list(root);
//cleaner(root);
system("pause");
return 0;
}
NetBeans:
收到信号:SIGTRAP (?) with sigcode ? (?) 从过程:? 对于程序列表,pid -1
您可以丢弃或转发信号,您可以继续或暂停该过程 要控制捕获或忽略哪些信号,请使用 Debug->Dbx Configure
Visual Studio:
调试错误!
检测到堆损坏:在正常块 (#57) 之后 0x00393230 CRC 检测到应用程序在堆缓冲区结束后写入内存。
(每次cleaner() 尝试释放列表项时,我都会收到#57、#58、...、#68 这个错误)
【问题讨论】:
-
“堆损坏”是一个直接的暗示,你在使用指针时犯了某种错误,顺便说一句。结束分配,双重释放,跟随未初始化的指针,......很多选择,但所有 pointer 相关。在这种情况下,这似乎不是很有帮助,但值得记住。