Reputation: 51
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;
}
Upvotes: 5
Views: 5030
Reputation: 183
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:
LD_LIBRARY_PATH=YOUR_GCC_INSTALLATION/lib64 ./hello
# Or
LD_LIBRARY_PATH=YOUR_GCC_INSTALLATION/lib64/libstdc++.so ./hello
If so, put the definition as system wide:
sudo echo "LD_LIBRARY_PATH=YOUR_GCC_INSTALLATION/lib64" >/etc/profile.d/your_gcc
and reboot.
Upvotes: 0
Reputation: 1516
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.
Upvotes: 1
Reputation: 143755
There's nothing wrong with that code, so you will have to investigate first your compiler, then your hardware.
Upvotes: 1
Reputation: 24130
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.
Upvotes: 6
Reputation: 13099
This might be a longshot, but try to change int main()
to int main(int argc, char *argv[])
Upvotes: 0