2

Below is a small portion of the source code where fclose is causing error? This function is not called always, at some particular condition this function is called.

int write_into_file (char * file_name)
{       
    FILE * fp = NULL ;

    if (file_name == NULL)
    {   
        return FAIL ; 
    }   

    if ((fp = fopen (file_name , "r")) == NULL)
    {   
        if ((fp = fopen (file_name, "w")) == NULL)
        {
            return FAIL ;
        }
    }
    fclose (fp) ;
    fp = NULL ;

    return SUCESS;

}

We are passing character buffer of size 1024 to file_name. Please can anyone tell me why fclose causes segmentation fault?

一二三
  • 21,059
  • 11
  • 65
  • 74
Nikhil
  • 576
  • 1
  • 11
  • 31
  • 4
    Try running it through `gdb` or `valgrind` as a start. Nothing looks immediately wrong with the code, so you should provide as much information about the crash as possible. It seems unlikely that `fclose()` is the real culprit. – Dan Fego Jan 03 '12 at 19:00
  • 1
    Is the character buffer null terminated? Is the character buffer a valid filename? Why are you opening the file for reading, then attempting to open it for writing if that fails? – Joseph Stine Jan 03 '12 at 19:01
  • Possible duplicate of [fclose() causing segmentation fault](http://stackoverflow.com/questions/1443164/fclose-causing-segmentation-fault) – Jim Fell Nov 13 '15 at 22:22

2 Answers2

5

I see no possible way that fclose could be causing a segfault here, I think your problem lies somewhere else in the program.

It might be possible that the stack got corrupted elsewhere, and that the bug shows when fclose gets called. I suggest you to review your other source code once more, and step over it with a debugger/memory analyzer closely watching what happens.

The only other thing I can see that might cause a bug is file_name not being null-terminated.

orlp
  • 112,504
  • 36
  • 218
  • 315
  • thanks for the reply. Yes, file_name is been null-terminated. I think I must check with valgrind. – Nikhil Jan 03 '12 at 19:10
2

There is no problem with fclose(). The problem could be with your comparison of file_name to NULL or it could be with some other part of your code.

Froyo
  • 17,947
  • 8
  • 45
  • 73