Segfault during fclose ()

fclose () calls segfault. I have:

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

I do not make any files associated with the file ... but nonetheless, this does not affect it. However, my MAIN process communicates with another process through shared memory, where pipeName is stored; another process captures this read pipe for communication with the MAIN.

Any ideas why this causes segfault?

Thank you Christo

+4
source share
3 answers
  • Go pipeFD to fclose . fclose closes the file with the file descriptor FILE* not filename char* . With C (unlike C ++), you can do implicit type conversion of pointer types (in this case char * to FILE *), so where does the error come from.

  • Make sure pepeFD is not NULL before calling fclose .

Edit: you have confirmed that the error was caused by a fopen failure, you need to check the error as follows:

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

Output Example:

The following error occurred: no such file or directory

+2
source

A failure in fclose implies that the FILE * passed to it was somehow damaged. This can happen if the pointer itself is damaged (check in your debugger to make sure it has the same value in fclose as fopen returned), or if the FILE data structure is corrupted by some random record entries or buffer overflows somewhere .

You can try using valgrind or some other memory corruption check to see if it can say anything. Or use a data breakpoint in your debugger at the address of the pipeFD variable. Using a data breakpoint in FILE itself is as complex as a few words and is modified using the usual file I / O.

+2
source

You should close pipeFD instead of pipeName.

+1
source

Source: https://habr.com/ru/post/1305947/


All Articles