[Solved] segmentation fault filing sleep function


The else branch of the if(fsize==0) conditional in csvwrite() does not fclose(fe). There is a limit on the number of files that can be opened by any one process at once; if you call this enough times, you’ll hit the limit, and the next fopen() will return NULL (and errno will be set to EMFILE – “Too many open files”).

That may or may not be the problem, so here’s some more general advice:

  1. Use a debugger. If you don’t know how, you should learn! For example:

    $ cat test.c
    #include <stdio.h>
    
    int main(void)
    {
        int a = 123, b, c;
        int *p = &a;
        int *q = NULL;
    
        b = *p;
        c = *q;
        printf("%d %d\n", b, c);
        return 0;
    }
    $ gcc -Wall -o test test.c
    $ ./test
    Segmentation fault
    $
    

    Not very helpful. But compile with -g and run it with gdb:

    $ gcc -g -Wall -o test test.c
    $ gdb ./test
    GNU gdb 6.8-debian
    Copyright (C) 2008 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "i486-linux-gnu"...
    (gdb) run
    Starting program: /tmp/test 
    

    …and it will reveal the line where it fails:

    Program received signal SIGSEGV, Segmentation fault.
    0x080483d4 in main () at test.c:10
    10        c = *q;
    (gdb) quit
    The program is running.  Exit anyway? (y or n) y
    $ 
    
  2. Compile with warnings enabled (as I have done above with the -Wall flag). The compiler is capable of spotting quite a lot of silly things, but you have to ask it.

  3. Try indenting the code sensibly. Readable code is easier to debug.

  4. Remember to check return values. fopen() in particular can fail for any number of reasons which are unrelated to your program.

  5. Don’t write vast amounts of practically identical code. If you have to do the same job more than once, consider factoring it out into a separate function.

1

solved segmentation fault filing sleep function