Normally when you call assert(foo())
and the assertion fails, the program automatically aborts. Is there any way to add some sort of handler that can clean up some resources before exiting?
Asked
Active
Viewed 407 times
0

Matt
- 21,026
- 18
- 63
- 115
-
2You can add a signal handler for `SIGABRT`. – jxh Mar 14 '13 at 00:22
-
IF the code is on UNIX/Linux, yes, good answer +1 – jim mcnamara Mar 14 '13 at 00:23
2 Answers
3
You can handle the SIGABRT
signal and do cleaning. Of course assert is just for debugging the application, so it is better to just fix the problem causing the failure instead of writing code to gracefully fail.

perreal
- 94,503
- 21
- 155
- 181
-
A good strategy, but you can also just define your own `assert` macro. – Eric Urban Mar 14 '13 at 00:32
-
yes that's another option but then, it is not the assert() in assert.h :) – perreal Mar 14 '13 at 00:34
-
Well the thing is even though it is just debugging, not cleaning stuff up screws up my filesystem (of course I'm doing all this in `/tmp`!). – Matt Mar 14 '13 at 00:35
0
The whole point of assert is to dump __FILE__
and __LINE__
information and call abort() immediately. If you don't want to do that, roll your own error checking with a cleanup handler, or do as suggested in another answer and catch the abort() itself. To your specific question, assert is just a macro, so you can't hook it directly. For chapter and verse, see ISO C99, 7.2.1, p2.

Randy Howard
- 2,165
- 16
- 26