views:

288

answers:

4

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: 

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

Viktor Sehr
Hi Viktor, I tried that and it compiled uneventfully. I ran it and got the same exact result. segmentation fault.
Jim
+5  A: 

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.

Martin B
Martin, I ran the first line and I never get the opportunity to enter anything else; the app just complies the out file.
Jim
@Jim: What's "the app"? What's "the out file"?
Alok
Sorry Alok. The app is the little hello world "application" and the out file is the file that was compiled and named a.out.
Jim
Am I running this correctly? I am running it like this: ./a.out
Jim
@Jim: Do you mean you ran `g++ -g -o hello hello.cpp` and it generated an `a.out` file and not a file named `hello`? (Even so, you can substitute `gdb a.out` for step 2.)
jamesdlin
@Jim: The "-o hello" option I added to the g++ command causes the compiler to write the executable to a file called "hello" (instead of the default, a.out, which is not usually what you want). Once this is compiled, use "gdb hello" to start the debugger, then enter the "run" command to run the program.
Martin B
+1  A: 

There's nothing wrong with that code, so you will have to investigate first your compiler, then your hardware.

Stefano Borini
Thanks. This seems to be the consensus but I have no idea how to troubleshoot at the server level.
Jim
+1  A: 

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.

Murali
+1 for the `-static` approach. However I do not believe that is has to do with LD_LIBRARY_PATH. I think that there is something wrong with the g++ installation.