Reputation: 6482
I'm using an external library (xqilla) for c++ that ends with a segmentation fault for some uri's, and some not. I'm a bit new to the whole C world, I'm guessing it's not possible to catch this as if it was an exception, but I need to ask if it's possible. Any other solution would of course also be welcomed.
So is there an alternative to try catch for a "Segmentation fault" error?
Upvotes: 2
Views: 3577
Reputation: 140659
I'm not familiar with xquilla specifically, but a "Segmentation fault" formally indicates that the program attempted to access a memory address that hasn't been allocated to it. With extremely rare exceptions (e.g. emulation of a different computer altogether) this indicates a catastrophic bug in the program. It is likely that, by careful manipulation of the input, the program can be made to misbehave in an arbitrarily malicious fashion rather than just crashing.
Your best option is to scrap this library and find one that does the same job but with fewer bugs.
If that's not an option, your second-best bet is to isolate the library in a separate process, running in a "sandbox" which prevents it from damaging anything when it crashes or is taken over by malware. The rest of your application would then detect the crash, clean up, and move on. Unfortunately, writing such a sandbox is Hard, and I don't know of any off-the-shelf code you can use. Good luck!
Upvotes: 2
Reputation:
If you are receiving a segmentation fault with a third party library, you should first narrow the scope of the problem and make sure that the bug is in your program and not the library. In the event of it being the fault of the library, you could save a lot of wasted effort by reporting the bug to the maintainer or searching the mailing list, documentation, etc.
Once you've gotten past this and decide to debug your program, capturing the "segmentation fault" is not what you want to do. The behavior is undefined at this point1. You should compile with -g
(if on GCC or Clang) to generate debugging information and run it with a debugger. There are several tools that can help you catch and fix bugs:
-Wall -Wextra -pedantic
-fsanitize=undefined,address,leak
2You will save a lot of effort by following the normal route of fixing your program instead of a backhanded way.
1) Source: Segmentation fault handling
2) Don't run valgrind and the sanitizer at the same time. Some sanitizers are mutually exclusive as well.
Upvotes: 3
Reputation: 224962
If you run your program in a debugger, it will tell you what instruction caused the bad memory access in question, so that you can fix it.
Alternatively, you can add a signal handler via signal(2)
or sigaction(2)
, but your ability to debug in that way will probably be pretty difficult. The state of your program after such a fault is probably unpredictable.
Upvotes: 7