我是 C 新手,在 Linux 中使用带有开关的 gcc4.4.6 进行编程gcc -g -std=c89 -Wall ...
,并且在我的程序深处的许多函数中都遇到了这个错误,名为compute
:
*** glibc detected *** ./compute: corrupted double-linked list: 0x0000000001a770b0 ***
======= Backtrace: =========
/lib64/libc.so.6[0x366d475916]
/lib64/libc.so.6[0x366d4786a4]
./compute[0x406987]
./compute[0x407f0d]
./compute[0x408a41]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x366d41ecdd]
./compute[0x401769]
======= Memory map: ========
...
下面是一些伪代码(代码很长,这里只展示结构):
myPts = 100;
JDP = malloc( sizeof(double) * myPts);
if (JDP == NULL)
exit(27);
...
if (testCondition == 1) { /* my execution enters this if stmt here */
...
myPts = 200;
free(JDP);
JDP = malloc (sizeof(double) * myPts);
if (JDP == NULL)
exit(27);
myFunction(JDP, ...); /* array JDP is populated here */
...
} else {
JDP[0]=0;
}
myOtherFunction(..., JDP, ...); /* array JDP is used here */
free(JDP); /* this line produces error shown above */
return 0;
使用 gdb 单步执行代码,此错误在代码的第二行产生:free(JDP)
. 执行是这样的,数组JDP
被 malloc'ed 两次,它们之间有一个 free。这可能是错误的原因吗?我以前从未这样做过,希望我犯了一些简单的错误......
更新 1
只是想特别注意,使用 gdb 我确实通过第一个空闲和第二个 malloc 逐步执行代码,所以我知道代码通过了这些步骤。
如果上面的设计模式没有问题,还有哪些其他场景会导致free()
这个错误?