Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top