开发者

Cannot use fclose on output stream, input stream is fine

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 th开发者_如何学Gois 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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜