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;
}
A segmentation fault occurs when your program attempts to access an area of memory that it is not allowed to access. In other words, when your program tries to access memory that is beyond the limits that the operating system allocated for your program. Used to being properly initialized.
Most memory errors which aren't memory leaks end up resulting in a segmentation fault. A segmentation fault is raised when the operating system realizes that your program is trying to access memory that it shouldn't have access to.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With