Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of setjmp and longjmp in C when linking to C++ libraries

Tags:

c++

c

setjmp

I would like to use setjmp and longjmp in a C program that links to a library that is implemented in C++ (but has a C API).

The C++ code does do dynamic memory allocation and pointers get passed through the API, but as long as the C side of the code manages those (opaque) objects correctly, there shouldn't be any messing up when using longjmp, right?

I know it's not safe to use these functions in C++ code, but should it be safe in C code that is linked to C++ code?

like image 554
Posco Grubb Avatar asked Aug 31 '11 04:08

Posco Grubb


People also ask

What is the use of setjmp and longjmp?

setjmp and longjmp are a pair of C function facilitating cross-procedure transfer of control. Typically they are used to allow resumption of execution at a known good point after an error. Both take as first argument a buffer, which is used to hold the machine state at the jump destination.

What is the use of setjmp?

setjmp saves the current environment (the program state), at some point of program execution, into a platform-specific data structure ( jmp_buf ) that can be used at some later point of program execution by longjmp to restore the program state to that saved by setjmp into jmp_buf .

What is the difference between Goto longjmp () and setjmp ()?

What is the difference between goto and longjmp() and setjmp()? A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.

What is longjmp function?

The longjmp function restores a stack environment and execution locale previously saved in env by setjmp .


1 Answers

The fact that you call C++ functions from your C code does not make setjmp and longjmp more unsafe than they always are.

What's important is that if your library allocates resources you must have recovery code in place to ensure that those are released properly after longjmp is called. While this is likely easy for your own allocations, it may be hard or impossible for the C++ library depending on how the C interface you use is structured.

like image 101
Miguel Avatar answered Oct 04 '22 21:10

Miguel