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.
CodePudding user response:
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).