re: I'm an Expert in Memory Management & Segfaults, Ask Me Anything! VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Hi there, I am pleasantly surprised to discover this site. Some people using my code had segmentation fault, I'm looking for a way to generate con...
 

Unfortunately, it is not possible to "catch" a segfault, nor continue program behavior safely (if at all) after it has been raised. Therefore, you have to take the opposite approach, and log everything that happened leading up to the segfault.

You can also have your tester describe (or screen record, especially if it's a game) what happened leading up to the segmentation fault. Then, you should be able to replicate that on your own machine.

Mind you, "replication" won't necessarily mean you can recreate the segmentation fault itself, since it's one of an infinite number of possible behaviors in response to some illegal memory action your code is taking (ergo "it is legal for the compiler to make demons fly out of your nose"). That's what it meant by undefined behavior. However, by replicating the same steps as your tester while running the Debug build of the application (compiled with -g) under Valgrind, you should be able to catch the problem.

There is also a more proactive approach you can take, especially if you're using C++: modernize your code base. Refactor the code - by hand mind you, NOT by using find-and-replace or some other automated tool - to make use of smart pointers like std::unique_ptr and std::shared_ptr instead of raw pointers, new, and delete. This will eliminate most memory errors, since the smart pointers handle object lifetime and whatnot (formally known as RAII). Refactoring is not a "quick fix", but it's the most resilient fix.

 

Thank you very much. You confirmed my approach is right: cout everything!

In my specific case, my code is appended to third party code where the segfault happens, so it's hard to trace and I don't even have the chance to fix.

At the risk of self-promotion, I wrote something called IOChannel which is designed to better control cout-style logging, based on category and priority. You can also route messages to different places, including to functions that will write them out to a file instead of printing them to the console. It's part of PawLIB, which is still in development, but 1.0 is stable. (Yes, totally open source)

code of conduct - report abuse