Search code examples
cfaultfclose

Fclose causing seg fault in C


I keep getting a seg fault if and only if I attempt to close a file:

   FILE *outFilePtr = fopen(*(argv + 2), "w"); //open file, yes i'm sure it opens


   fclose(outFilePtr); //sometime later in the program.

The program runs from start to finish without the flcose(). Any suggestions?

The error on gdb redirects here: Assume it is a function with all variables declared. Also gdb blames strtol which I'm not even using.

 int t;
     char line[50];

          for (t = 0; t < lines; t++){
              fgets(line, 50, filePtr);
             strcpy(*string[t], strtok(line, " "));
              *(num1 + t) = atoi(strtok(NULL, " "));
              *(num2 + t) = atoi(strtok(NULL, " "));
           }

Memory Allocation Function

 void dynamicArray(int** num1, int** num2, char*** str, int size)
 { 
     int i = 0;

*(num1) = (int*)malloc(sizeof(int) * size);
*(num2) = (int*)malloc(sizeof(int) * size);

*(str) = (char**)malloc(sizeof(char*) * size);

for( i = 0; i < size; i++){
    *(*(str) + i) = (char*)malloc(sizeof(char) *size);
}

return;
 }

Solution

  • Just to be sure, check that outFilePtr is not null:

    if (outFilePtr) {fclose(outFilePtr); outFilePtr = NULL;}
    

    I always do it when closing the file and I also put the pointer to NULL to avoid trying to close the same file twice (that may cause trouble as well).

    But most likely the cause is some memory leak or undefined behaviour that messes things around and segfault is just triggered by the fclose().