1

I find it hard to believe, but code that throws a VCL Exception somehow leaks memory.

Have created a MVE to convince myself that this is really happening.

So here's a basic C++ console application, using VCL, that just repeatedly throws the same exception and tries to catch it.

#include <vcl.h>
#include <windows.h>

#pragma hdrstop
#pragma argsused

#include <tchar.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    while (true){
        try {
            throw Exception(L"This is my Exception Message");
        } catch (const Exception & e) {
        }
    }

    return 0;
}

When you run this code outside the debugger, it leaks like a seave. If you run this code under the debugger, it leaks at a slower rate.

If you instead pass an integer (i.e. throw Exception(42)), there is still a leak. At this point I was hoping to avoid the complicated dance that UnicodeString performs.

The question is: why does this leak? Have I missed something or am I using Exception the wrong way?

Found this to happen at least with XE7. With XE11, the leak only occurs if the exception is thrown from a subroutine. (these are the only versions available to me). We have the JCL library installed, if that's a factor.

E. van Putten
  • 615
  • 7
  • 17
  • Somebody asked basically the same question here, but for XE2: https://codeverge.com/embarcadero.cppbuilder.cpp/memory-leak-when-catching-exceptio/1057044 – E. van Putten Aug 10 '22 at 20:07
  • 1
    In my experience, exceptions often lead to destructors not being called for local variables (even for non-VCL classes). The solution is to update C++ Builder and stop using the classic compiler (Project Options -> C++ Compiler). – VLL Aug 18 '22 at 10:14
  • 1
    There are a few open bugs related to this problem in the embarcadero Jira website. One is RSP-27271 in quality.embarcadero.com . – CuriousNik Aug 19 '22 at 11:33
  • With the new RAD Studio 11 and clang compiler things indeed look better than before. – E. van Putten Aug 23 '22 at 15:38
  • @VLL care to convert your comment into an answer? – E. van Putten Aug 24 '22 at 09:13

1 Answers1

2

In my experience, exceptions often lead to destructors not being called for local variables (even for non-VCL classes). In this case, it seems destructor isn't even called for Exception class itself.

Possible solution is to update C++ Builder and stop using the classic compiler (Project Options -> C++ Compiler).

The exact memory leak in your question is reported fixed in version 10.3.0 (RSP-11916), and reported broken again (still open) in version 10.3.2 (RSP-27271). Another report says this only occurs in modern versions when optimizations are not enabled (RSP-30118).

VLL
  • 9,634
  • 1
  • 29
  • 54