C语言free函数出错,求解!
首先请看如下源代码:
/*
* rl.c - Reverse a list
*/
#include
#include
struct node {
int data;
struct node *next;
};
struct node *create_list(int array[], int length) {
int i = 0;
struct node *head, *p;
head = (struct node *) malloc( sizeof(struct node) * length );
for ( i=0; i
p = &(head[i]);
p->data = array[i];
p->next = &(head[i+1]);
}
p = &(head[i]);
p->data = array[i];
p->next = NULL;
return head;
}
struct node *reserve_list(struct node *list) {
struct node *p, *prev, *next;
for (p = list, prev = NULL; p; p = next) {
next = p->next;
p->next = prev;
prev = p;
}
return prev;
}
void free_list(struct node *list) {
free(list);
}
int main()
{
struct node *p;
int source[10] = {1,2,3,4,5,6,7,8,9,10};
p = create_list(source, 10);
p = reserve_list(p);
free_list(p);
}
该源代码用命令行:
gcc -o rl rl.c
进行编译,得到应用程序rl,运行该应用程序后,出现如下错误:
$ ./rl
*** glibc detected *** ./rl: double free or corruption (out): 0x0000000000bf90a0 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7ec66)[0x7f04f776bc66]
./rl[0x400668]
./rl[0x4006e9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7f04f770e78d]
./rl[0x400489]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:51 794284 /media/DATA/projects/c-sample/rl
00600000-00601000 r--p 00000000 08:51 794284 /media/DATA/projects/c-sample/rl
00601000-00602000 rw-p 00001000 08:51 794284 /media/DATA/projects/c-sample/rl
00bf9000-00c1a000 rw-p 00000000 00:00 0 [heap]
7f04f74d7000-7f04f74ec000 r-xp 00000000 08:01 529232 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f04f74ec000-7f04f76eb000 ---p 00015000 08:01 529232 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f04f76eb000-7f04f76ec000 r--p 00014000 08:01 529232 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f04f76ec000-7f04f76ed000 rw-p 00015000 08:01 529232 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f04f76ed000-7f04f78a2000 r-xp 00000000 08:01 529443 /lib/x86_64-linux-gnu/libc-2.15.so
7f04f78a2000-7f04f7aa2000 ---p 001b5000 08:01 529443 /lib/x86_64-linux-gnu/libc-2.15.so
7f04f7aa2000-7f04f7aa6000 r--p 001b5000 08:01 529443 /lib/x86_64-linux-gnu/libc-2.15.so
7f04f7aa6000-7f04f7aa8000 rw-p 001b9000 08:01 529443 /lib/x86_64-linux-gnu/libc-2.15.so