tags:

views:

102

answers:

2

Whenever I run my program with fclose(outputFile); at the very end, I get an error. glibc detected...corrupted double-linked list

The confusing thing about this though, is that I have fclose(inputFile); directly above it and it works fine. Any suggestions?

FILE* inputFile = fopen(fileName, "r");
if (inputFile == NULL)
{
    printf("inputFile did not open correctly.\n");
    exit(0);
}
FILE* outputFile = fopen("output.txt", "wb");
if (outputFile == NULL)
{
    printf("outputFile did not open correctly.\n");
    exit(0);
}

/* ... read in inputFile ... */
/* ... some fprintf's to outputFile ... */

fclose(inputFile);
fclose(outputFile);
A: 

The problem is likely located in this section:

 /* ... read in inputFile ... */

You've got some code there that corrupts the heap. Overflowing an array is the typical cause. Heap corruption is rarely detected at the time the corruption happens. Only later, when some code allocates or releases memory and has some basic heap health verification built in. Like fclose() does.

Hans Passant
why would it not pick it up in the first fclose though?Thanks for the suggestion though, I'm not very proficient with pointers, would that also cause the same problem?
TeeJay
Heap corruption never behaves predictably, it entirely depends on where the damage was done. Yes, pointers are the number one way to blow the heap.
Hans Passant
Hrmm, well it seems semi-predicatable. I've run the program numerous times with the second fclose commented out and it never has a problem (not a glibc problem anyway).Thanks for the help, it's a large-ish program so I'll see if I can figure it out with valgrind and gdb.
TeeJay
A: 

To detect exactly where your code is corrupting the heap, if you are running on Linux, you should use valgrind. It's easy to use:

valgrind ./myprog arguments ...

and will give you a stack trace from the exact point where a bad read or write occurs.

Valgrind is available from major Linux distributions or you can build from source.

Norman Ramsey