[Bug c++/102237] New: longjmp leaks catched std::runtime_error
david.cortes.rivera at gmail dot com
gcc-bugzilla@gcc.gnu.org
Wed Sep 8 02:19:21 GMT 2021
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102237
Bug ID: 102237
Summary: longjmp leaks catched std::runtime_error
Product: gcc
Version: 10.3.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: david.cortes.rivera at gmail dot com
Target Milestone: ---
Created attachment 51425
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=51425&action=edit
ii_file
I am experiencing a memory leak when using long jumps from a catch block in
which the jump takes to a different function. Basically, the exception objects
are not getting destructed.
>From what I gather from this SO question:
https://stackoverflow.com/questions/69092014/c-will-an-stdruntime-error-object-leak-in-a-longjmp
calling something like "catch(std::exception &e) {longjmp(jump_buffer, 1);}"
should be allowed by the standard, and the exception should be destructed along
the way.
For example, the following code ***works as expected***:
-------
#include <stdexcept>
#include <stdio.h>
#include <setjmp.h>
void my_fun()
{
jmp_buf jump_buffer;
if (setjmp(jump_buffer))
return;
try {
std::string message;
message.resize(100);
snprintf(&message[0], 100, "error code %d\n", 3);
throw std::runtime_error(message);
}
catch (std::runtime_error &e) {
longjmp(jump_buffer, 1);
}
}
int main()
{
for (int ix = 0; ix < 100000; ix++)
void my_fun();
return 0;
}
-------
...
But ***if I switch the jump buffer to be outside of the function***, it will
now start leaking memory at each call:
-------
#include <stdexcept>
#include <stdio.h>
#include <setjmp.h>
jmp_buf jump_buffer;
void my_fun()
{
try {
std::string message;
message.resize(100);
snprintf(&message[0], 100, "error code %d\n", 3);
throw std::runtime_error(message);
}
catch (std::runtime_error &e) {
longjmp(jump_buffer, 1);
}
}
void call_myfun()
{
if (setjmp(jump_buffer))
return;
my_fun();
}
int main()
{
for (int ix = 0; ix < 100000; ix++)
call_myfun();
return 0;
}
-------
Setup info:
- AMD Ryzen 7 2700.
- Debian linux (sid)
- gcc --version: gcc (Debian 10.3.0-9) 10.3.0
The source file is compiled with the default options (g++ file.cpp). The leak
is detected by valgrind-3.16.1.
Attached is the .ii file.
More information about the Gcc-bugs
mailing list