Search code examples
ccygwinstdio

Segmentation fault calling setvbuf


I'm trying a basic program with setvbuf:

int main(int argc, char **argv) {

    FILE * fp;
    char buffer[1024];

    fp = fopen("~/my.txt", "w");

    setvbuf(fp, buffer, _IOFBF, sizeof(buffer));

    return EXIT_SUCCESS;
}

When I run the program, I hit a segmentation fault on setvbuf:

Breakpoint 1, main (argc=0, argv=0x20) at ../my.c:13
13      int main(int argc, char **argv) {
(gdb) n
18              fp = fopen("~/my.txt", "w");
(gdb) n
20              setvbuf(fp, buffer, _IOFBF, sizeof(buffer));
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()

My environment is:

$ uname -a
CYGWIN_NT-6.1 myhost 1.7.25(0.270/5/3) 2013-08-31 20:37 x86_64 Cygwin
$ gcc --version
gcc (GCC) 4.8.1

Solution

  • As informed by Oli's comment and Paul R's comment, I added the appropriate error handling:

    fp = fopen("~/my.txt", "w");
    if (fp == NULL)
      {
        perror ("The following error occurred");
        printf( "Value of errno: %d\n", errno );
        return EXIT_FAILURE;
      }
    

    And the output was:

    The following error occurred: No such file or directory
    Value of errno: 2
    

    After fixing the file path to a full path, the call to setvbuf was successful.