| vincegata (70) | |
|
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! | |
|
|
|
| Peter87 (2052) | |
|
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. | |
|
|
|
| vincegata (70) | |
|
I see, I need to start reading on valgrind - thank you! | |
|
|
|
| vincegata (70) | |||
I found the source of my Segmentation fault with Valgrind however I would have expected to get an Index out of range exception.
Could someone comment why it was not an exception? I am new to programming in Linux. Thanks! | |||
|
|
|||
| Peter87 (2052) | |
| Arrays are not bound checked in C++. Accessing an array out of bounds gives undefined behaviour which means anything could happen. | |
|
|
|
| vincegata (70) | |
| Thanks again. | |
|
|
|
| Luc Lieber (732) | |||
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.
| |||
|
Last edited on
|
|||
| vincegata (70) | |
|
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
|
|
| Peter87 (2052) | |
| 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
|
|
| vincegata (70) | |
| THX | |
|
|
|
| LauraArnold (3) | |
|
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 | |
|
|
|
| vincegata (70) | |
| I marked it as Solved :) | |
|
|
|