I'm working with Lua, which has a C API and its error raising functions use longjmps. When raising an error I first build a message describing what went wrong and then tell Lua to raise the error. For example
std::stringstream ss;
ss << "'" << function->cb->name << "' expects at most " << maxargs_all
<< " argument(s) and received " << nargs;
luaL_error(L, ss.str().c_str());
It's my understanding that longjmp won't unwind the stack and so my stringstream
object won't be destroyed. If I remember correctly, stringstream
and other C++ library classes typically allocate data on the heap, which is freed when the object is destroyed. However, the destructor won't be called here and so I think this will result in a memory leak. Depending on the person who wrote the script, I could potentially be raising a lot of errors and thus leaking a lot of memory.
I'm sure other people have needed to solve a similar problem to this, but I can't find anything that's quite what I'm after. A lot of places say the objects won't get destroyed, but I would assume there must be a way to ensure the memory is freed?
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.
Remarks. The longjmp function restores a stack environment and execution locale previously saved in env by setjmp .
So, when you call setjmp(), you pass it the address of an array of integers, and it stores the value of the registers in that array. Setjmp() returns 0 when you call it in this way. longjmp(jmp_buf env, int val); Longjmp() resets the registers to the values saved in env.
5.1 Concept. Longjump is a programming concept used in C to manipulate the flow of the execution sequence. Roughly it can be described as setting a mark by saving the current state of the processor of a program - in this case a thread or a process.
The solution is to compile Lua as a C++ library. Then luaL_error()
will throw an exception instead of calling longjmp()
and everything will be destroyed by stack unwinding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With