Question

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 do 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

Was it helpful?

Solution

  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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top