我在释放杀戮过程中的最后一个 struct bbb
变量时会崩溃。但是为什么为什么呢?假设free
中某个地方的问题
struct bbb
{
struct bbb * h;
char a [256];
int i;
};
void kill(struct bbb * value)
{
if (value!=NULL)
{
kill(value->h);
printf("killing %sn", value->a);
free(value);
printf("killedn");
value=NULL;
}
}
void ins(struct bbb * b, struct bbb * a )
{
b->h= malloc(sizeof(struct bbb ) );
b->h[0]=*a;
}
int main(void) {
struct bbb a;
struct bbb b;
struct bbb c;
//ss=s;
sprintf(a.a,"aaa" );
sprintf(b.a,"bbb" );
sprintf(c.a,"ccc" );
ins(&b,&c);
ins(&a,&b);
kill(&a);
//printf("a.a=%sn",a.a);
return EXIT_SUCCESS;
}
输出:
killing ccc
killed
killing bbb
killed
killing aaa
*** glibc detected *** /home/aaa/workspace_train/SmallTest/Debug/SmallTest: double free or corruption (out): 0x00007ffff0fe3d20 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7fa77ec56b96]
/home/gedas/workspace_train/SmallTest/Debug/SmallTest(kill+0x48)[0x400e15]
/home/gedas/workspace_train/SmallTest/Debug/SmallTest[0x400ef9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fa77ebf976d]
您在堆栈上分配了a
,然后尝试使用free
的地址。您只能使用Malloc或类似功能获得的指针免费致电。
我认为不需要那个malloc,这是我的解决方案:
struct bbb
{
struct bbb * h;
char name [256];
int i;
};
void _kill(struct bbb * value)
{
if (value!=NULL)
{
_kill(value->h);
printf("killing %sn", value->name);
value->h=NULL;
value=NULL;
printf("killedn");
}
}
void ins(struct bbb * b, struct bbb * a )
{
// b->h= malloc(sizeof(struct bbb *) );
b->h= a;
}
int main(void) {
struct bbb a;
struct bbb b;
struct bbb c;
//ss=s;
sprintf(a.name,"aaa" );
sprintf(b.name,"bbb" );
sprintf(c.name,"ccc" );
ins(&b,&c);
ins(&a,&b);
_kill(&a);
//printf("a.a=%sn",a.a);
return EXIT_SUCCESS;
}