Search code examples
cstack-overflowabort

Does the abort() function in C clean the stack?


It's possible to catch the SIGABRT and continue the program with a longjump for example.

I wonder if this can lead to a stack overflow when I always call functions that invoke abort().

I need to know that because i want to use the assert macro (taht calls abort) in unit tests. If an assert fails, I want to continue with the next unit test.


Solution

  • abort doesn't need to clear the stack; longjmp will "clear" it in that it will rewind the stack pointer back to the position of setjmp. If all else is correct, repeatedly invoking longjmp and setjmp will not cause stack overflow.

    However, longjmp will skip normal execution path, which can call resource leaks in its own right. Consider this code:

    char *s = malloc(...);
    ... use s ...
    free(s);
    

    If the "... use s ..." portion calls some function that longjmps out of the code, free won't get a chance to get called and you will leak. The same applies to closing open files, sockets, freeing shared memory segments, reaping forked children, and so on.

    For this reason longjmp is rarely used in C programming. My advice would be to avoid assert if you don't mean the program to exit. Simply use another macro in your unit tests, or switch to a testing framework that provides one.