views:

153

answers:

3

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

+1  A: 

You should close pipeFD instead of pipeName.

WhirlWind
my apologies... I do close pipeFD... that is a mistype
Hristo
+1  A: 
  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

Brian R. Bondy
1. That was a mistype. I do pass pipeFD to fclose(). 2. I put in a check for NULL, and it turns out that it is NULL. How does that make work? I thought fopen creates the file if that file name doesn't exist?
Hristo
fopen is failing for whatever reason. What is perror()?
WhirlWind
@Hristo: You can't do a close unless the fopen succeeds. fopen is currently failing you need to check the error to see why.
Brian R. Bondy
@Hristo: See my code example I put in the edit
Brian R. Bondy
yes fopen is failing. I just substituted in a "w+" instead of a "w" to fopen and it seems to work now... not sure why. but i don't necessarily want to read and write.
Hristo
@Hristo: What did the error say by the way for perror?
Brian R. Bondy
Interrupted system call
Hristo
A: 

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.

Chris Dodd
Thanks for your reply. It turns out fopen was failing.
Hristo