views:

247

answers:

4

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!

+1  A: 

Does "Hello world!" program seg fault? If so then you have a hardware problem. If not then you have at least one problem in the code you're not showing us!

David Harris
+7  A: 

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.

wallyk
Thank you! This is basically what I was trying to get at. OK, great.
AlexeyMK
Using GDB will allow you to locate segfaults instantly, and also allow you to peruse the stack to locate any potentially wonky values.
Chris
I'm reading a number of GDB tutorials now. But if my program only seg-faults at the very end, what should I be looking for above? Any recommended techniques?
AlexeyMK
Well start with seeing what operation caused the segfault in GDB. Without that, you can't go much further.Just do gdb your-appWhen started, type `run`, then `backtrace` after the segfault to examine the stack. You don't need to know any more about gdb than that.
McPherrinM
If the cause is indeed trashing the stack, GDB will show a confused looking stack. It probably won't make any sense at all.
wallyk
A: 

Compile your program with the debug flag gcc -g and run your code in gdb. You can't always trust the console to output "Segmentation fault" exactly when problematic code is executed or relative to other output. In many cases this will be misleading -- you will find debugging tools such as gdb extremely useful.

ty
+1  A: 

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.

3lectrologos
Thank you! I later found this myself. valgrind is awesome.
AlexeyMK