开发者

Why am I getting a segmentation fault?

开发者 https://www.devze.com 2022-12-17 06:02 出处:网络
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 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;
}


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:

g++ -g -o hello hello.cpp

then run gdb:

gdb hello

and at the gdb prompt type

run

to run the program. When it crashes, type

bt

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.


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.


This might be a longshot, but try to change int main() to int main(int argc, char *argv[])

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号