Reputation: 4246
I'm new to C, programming in Linux using gcc4.4.6 with switches gcc -g -std=c89 -Wall ...
, and I'm getting this error many functions deep in my program named 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: ========
...
Here's some pseudo-code (the code is very long, so I'm only showing the structure here):
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;
Stepping through the code using gdb, this error is produced on the 2nd line of code for: free(JDP)
. The execution is such that array JDP
is malloc'ed twice, with a free between them. Could this be the cause of the error? I've never done this before, and hoping there's some simple mistake I'm making...
UPDATE 1
Just wanted to specifically note that using gdb I do step the code through the first free and 2nd malloc, so I know the code passes through these steps.
If the design pattern above isn't a problem, what other scenarios would result in free()
leading to this error?
Upvotes: 1
Views: 187
Reputation: 140659
There is nothing obviously wrong with the code you have shown. In particular the code pattern
x = malloc(n);
...
if (condition) {
free(x);
x = malloc(m);
}
...
free(x);
is not wrong in and of itself.
You have almost certainly made a simple mistake somewhere in the code you did not show, which has caused memory corruption. Fortunately there is an excellent tool for finding such mistakes automatically: it's called valgrind
. Run your program under this tool. Fix the very first error it tells you about. Repeat until it tells you of no further errors. (Often only the very first of valgrind's complaints reflects a real bug in your code; all the subsequent complaints are "merely" fallout from the original bad memory access.)
Upvotes: 2
Reputation: 12040
Freeing the variable twice is fine so long as you're mallocing separately between them. I would suspect the issue is that you aren't actually mallocing between them - some logical switch (if/else/while) is preventing the malloc
from taking place, thus the free
occurs twice on the same pointer.
Upvotes: 1