Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bizarre/Random Segfault in C

EDIT: Clarifying.

  • fout is is a FILE*. (I thought this was irrelevant since that line clearly compiles)
  • there is A LOT of code above these last few lines; I guess I could dump them all but I imagine you're not overly interested in debugging my stuff. I'm more interested, generally, in what could possibly occur that would segfault at return 0 but not before.

Warning: My C is terrible.

I've got a C program which, from the likes of it, just wants to segfault. I'll spare you the other, irrelevant details, but here's the big picture:

My code:

//...other code
printf("finished \n");   
fclose(fout);   
printf("after fclose \n");  
return 0;

The output:

finished
after fclose
Segmentation fault

I'm compiling with GCC, -std=c99.

My question:

How the heck is this even possible? What should I be looking at, that may be causing this (seemingly random) segfault? Any ideas?

Much thanks!

like image 532
AlexeyMK Avatar asked Feb 05 '26 19:02

AlexeyMK


2 Answers

Whatever the return is going back to is causing the fault. If this code snippet is in main(), then the code has inflicted damage to the stack, most likely by exceeding the bounds of a variable. For example

int main ()
{
    int a [3];
    int j;

    for (j = 0;  j < 10;  ++j)
         a [j] = 0;
    return 0;
}

This sort of thing could cause any of a number of inexplicable symptoms, including a segfault.

like image 92
wallyk Avatar answered Feb 07 '26 07:02

wallyk


Since it's probably a stack corruption related problem, you could also use a memory debugger to locate the source of the corruption, like valgrind.
Just compile using gcc -g and then run valgrind yourprog args.

like image 29
3lectrologos Avatar answered Feb 07 '26 07:02

3lectrologos