开发者

segfault during fclose()

fclose() is causing a segfault. I have :

char buffer[L_tmpnam];
char *pipeName = tmpnam(buffer);
FILE *pipeFD = fopen(pipeName, "w"); // open for writing
...
...
...
fclose(pipeFD); 

I don't d开发者_如何学JAVAo any file related stuff in the ... yet so that doesn't affect it. However, my MAIN process communicates with another process through shared memory where pipeName is stored; the other process fopen's this pipe for reading to communicated with MAIN.

Any ideas why this is causing a segfault?

Thanks, Hristo


  1. Pass pipeFD to fclose. fclose closes the file by file handle FILE* not filename char*. With C (unlike C++) you can do implicit type conversions of pointer types (in this case char* to FILE*), so that's where the bug comes from.

  2. Check if pepeFD is non NULL before calling fclose.

Edit: You confirmed that the error was due to fopen failing, you need to check the error like so:

 pipeFD = fopen(pipeName, "w");
 if (pipeFD == NULL)
 {
   perror ("The following error occurred");
 }
 else
 {
   fclose (pipeFD);
 }

Example output:

The following error occurred: No such file or directory


A crash in fclose implies the FILE * passed to it has been corrupted somehow. This can happen if the pointer itself is corrupted (check in your debugger to make sure it has the same value at the fclose as was returned by the fopen), or if the FILE data structure gets corrupted by some random pointer write or buffer overflow somewhere.

You could try using valgrind or some other memory corruption checker to see if it can tell you anything. Or use a data breakpoint in your debugger on the address of the pipeFD variable. Using a data breakpoint on the FILE itself is tricky as its multiple words, and is modified by normal file i/o operations.


You should close pipeFD instead of pipeName.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜