Reputation: 6395
EDIT: Clarifying.
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:
//...other code
printf("finished \n");
fclose(fout);
printf("after fclose \n");
return 0;
finished
after fclose
Segmentation fault
I'm compiling with GCC, -std=c99.
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!
Upvotes: 3
Views: 4801
Reputation: 2350
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!
Upvotes: 1
Reputation: 9662
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
.
Upvotes: 2
Reputation: 11132
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.
Upvotes: 0
Reputation: 57784
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.
Upvotes: 11