C 中的奇怪/随机段错误
编辑:澄清。
- fout 是一个 FILE*。 (我认为这是无关紧要的,因为该行显然可以编译)
- 最后几行上面有很多代码;我想我可以把它们全部转储,但我想你对调试我的东西不太感兴趣。一般来说,我更感兴趣的是在返回 0 时可能发生的段错误,而不是之前。
警告:我的 C 很糟糕。
我有一个 C 程序,从类似的程序来看,它只是想要出现段错误。我将省去您其他不相关的细节,但这是大局:
我的代码:
//...other code
printf("finished \n");
fclose(fout);
printf("after fclose \n");
return 0;
输出:
完成
fclose 之后
分段错误
我正在使用 GCC 进行编译,-std=c99。
我的问题:
这到底怎么可能?我应该注意什么,这可能会导致这种(看似随机的)段错误?有什么想法吗?
非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是否“你好世界!”程序段错误?如果是这样,那么你就有硬件问题了。如果没有,那么您未向我们展示的代码中至少存在一个问题!
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!
使用调试标志
gcc -g
编译程序并在gdb
中运行代码。您不能总是相信控制台在执行有问题的代码时或相对于其他输出准确地输出“分段错误”。在许多情况下,这会产生误导——您会发现诸如gdb
之类的调试工具非常有用。Compile your program with the debug flag
gcc -g
and run your code ingdb
. 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 asgdb
extremely useful.无论
返回
返回什么都会导致错误。如果此代码片段位于main()
中,则该代码很可能超出了变量的界限,从而对堆栈造成了损坏。例如,这种事情可能会导致许多无法解释的症状,包括段错误。
Whatever the
return
is going back to is causing the fault. If this code snippet is inmain()
, then the code has inflicted damage to the stack, most likely by exceeding the bounds of a variable. For exampleThis sort of thing could cause any of a number of inexplicable symptoms, including a segfault.
由于这可能是与堆栈损坏相关的问题,因此您还可以使用内存调试器来定位损坏的来源,例如 valgrind< /a>.
只需使用
gcc -g
进行编译,然后运行 valgrind yourprog args
即可。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 runvalgrind yourprog args
.