为什么我会出现分段错误?
我正在尝试用 C++ 编译一个简单的 hello world 函数。编译后,运行它并得到“分段错误”。有人可以解释一下吗?
我使用以下命令从 Linux 命令行编译此文件:
g++ 你好.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
I am trying to compile a simple hello world function in c++. After I compile it, I run it and get "Segmentation fault". Can someone shed some light on this?
I am compiling this from a Linux command line using the following command:
g++ hello.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
程序本身看起来还不错。我猜想您的编译环境中有一些怪癖导致了段错误。
最好的办法是在调试器(gdb)中运行它——这会告诉你它在哪里崩溃,这将帮助你找出问题所在。
为此,请像这样编译:
然后运行 gdb:
并在 gdb 提示符下键入
运行程序。当它崩溃时,输入
它将给你一个堆栈跟踪,希望它能帮助你弄清楚发生了什么。
The program itself looks OK. I would guess there's some quirk in your compilation environment that is causing the segfault.
Your best bet is to run this in the debugger (gdb) -- that will tell you where it's crashing, which will help you figure out what the problem is.
To do this, compile like this:
then run gdb:
and at the gdb prompt type
to run the program. When it crashes, type
which will give you a stacktrace that will -- hopefully -- help you figure out what's going on.
该代码没有任何问题,因此您必须首先检查您的编译器,然后检查您的硬件。
There's nothing wrong with that code, so you will have to investigate first your compiler, then your hardware.
编译它
像这样g++ -Bstatic -static hello.cpp
,然后运行 ./a.out
如果这没有出现段错误,那么 LD_LIBRARY_PATH 就是你的罪魁祸首。
Compile it like this
g++ -Bstatic -static hello.cpp
and then run ./a.out
If this doesn't seg fault, LD_LIBRARY_PATH is your culprit.
这可能不太可能,但请尝试将
int main()
更改为int main(int argc, char *argv[])
This might be a longshot, but try to change
int main()
toint main(int argc, char *argv[])
虽然已经晚了,但可能有用:
编译的一个简单的 cxx 程序会在核心转储/段错误的情况下运行,原因可能是:
这通常发生在 gcc 安装编译的情况下来源。
解决方法是通过 LD_LIBRARY_PATH 预加载正确的 lib64/ 文件夹:
如果是这样,请将定义设置为系统范围:
然后重新启动。
It's late but might useful:
A simple cxx program compiled runs with core dump / segment fault, the reasons could be:
This commonly happens in the gcc installation is compiled from source.
The workaround is preloading the right lib64/ folder via LD_LIBRARY_PATH:
If so, put the definition as system wide:
and reboot.