Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 282
osiris81 Avatar asked Jan 23 '13 13:01

osiris81


People also ask

What does abort () do in C?

In the C Programming Language, the abort function raises the SIGABRT signal, and causes abnormal program termination that returns an implementation defined code indicating unsuccessful termination.

What is the difference between abort and exit in C?

The difference between exit and abort is that exit allows the C++ runtime termination processing to take place (global object destructors get called). abort terminates the program immediately. The abort function bypasses the normal destruction process for initialized global static objects.

When can we use abortion?

Abort is preferred when application does not able to handle the exception and not able to understand what to do scenario. exit() mean application should must finish all task gracefully. if exception occurs and application is able to handle the same then exit() call happens.


2 Answers

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.

like image 54
user4815162342 Avatar answered Oct 09 '22 17:10

user4815162342


longjmp does not unwind the stack, but it does modify the stack pointer:

If the function in which setjmp was called returns, it is no longer possible to safely use longjmp with the corresponding jmp_buf object. This is because the stack frame is invalidated when the function returns. Calling longjmp restores the stack pointer, which—because the function returned—would point to a non-existent and potentially overwritten/corrupted stack frame.

like image 40
Dark Falcon Avatar answered Oct 09 '22 18:10

Dark Falcon