Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a segmentation fault?

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;
}
like image 295
Jim Avatar asked Jan 25 '10 10:01

Jim


People also ask

Why do I get segmentation fault C++?

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.

Does segmentation fault mean memory leak?

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.


3 Answers

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.

like image 191
Martin B Avatar answered Oct 19 '22 22:10

Martin B


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

like image 24
Stefano Borini Avatar answered Oct 19 '22 23:10

Stefano Borini


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.

like image 26
Murali Avatar answered Oct 19 '22 22:10

Murali