I get "Segmentation fault"

Hello,

I am sporadically getting "Segmentation fault" error. googling says that it happens when the program is trying to write to a memory segment that it does not have access to.

I use try-catch block on the out most program function (as below) but still my program shuts down abruptly without even going into catch block.

int main()
{
try
{
MyClass app = MyClass();
app.Run();
}
catch(exception& e)
{
cerr << "my app exception: " << e.What() << endl;
}
}

So, why try-catch is not catching it, and what is the way to determine what causes this error. I run Ubuntu, g++, it is sockets application.

TIA!

Reading and writing to invalid memory locations doesn't throw exceptions. It is undefined behaviour so the C++ standard gives no guarantees on what will happen.

If you want to find out where the problem occur you can use a memory debugger such as valgrind.
I see, I need to start reading on valgrind - thank you!
I found the source of my Segmentation fault with Valgrind however I would have expected to get an Index out of range exception.

1
2
3
4
5
6
TickClass tick[5];
for(int i=0;i<5;i++) tick[i] = TickClass();

int j = -1;
tick[j].get_symbol(); //  Segmentation fault is here.


Could someone comment why it was not an exception? I am new to programming in Linux. Thanks!
Arrays are not bound checked in C++. Accessing an array out of bounds gives undefined behaviour which means anything could happen.
Thanks again.
closed account (3hM2Nwbp)
If you want bounds checking, you can use a std::vector.

Keep in mind however, that std::vector::operator[] does not provide bounds checking, whereas std::vector::at does.

1
2
3
4
5
6
7
8
9
std::vector<TickClass> ticks;
for(int i=0;i<5;i++)
{
  ticks.push_back(TickClass());
}

int j = -1;
ticks[j].get_symbol(); //  Segmentation fault is here.
ticks.at(j).get_symbol(); // out_of_range thrown here. 
Last edited on
Thanks for the suggestion, I use STL vector in some other places but here I need my code to be as fast as possible hence the C-style array. vector is probably adding some performance overhead for all those niceties.

It's just I remember getting more meaningful messages for array out of bounds error when I was coding with Visual C++ & Windows - not that I regret abandoning Windows :)
Last edited on
std::vector::operator[] shouldn't have any overhead with optimizations turned on. You can enable bounds checking for std::vector::operator[] (and other things like iterators) by defining the macro _GLIBCXX_DEBUG. That way you can have bounds checking while testing and when you later want speed you just remove it.
Last edited on
THX
Getting "Segmentation Fault" tells us that it doesn't work, but it's not enough for debugging. Can you try running ns2 with gdb and post the output you get?

http://www.versionfull.com/search/accounting-software/1
I marked it as Solved :)
Topic archived. No new replies allowed.