Below is the original Delphi source code of TNetEncoding.GetBase64Encoding
. But I suspect there will be a memory leak in case AtomicCmpExchange(Pointer(FBase64Encoding), Pointer(LEncoding), nil) <> nil
TNetEncoding = class
private
class var
FBase64Encoding: TNetEncoding;
with
class function TNetEncoding.GetBase64Encoding: TNetEncoding;
var
LEncoding: TBase64Encoding;
begin
if FBase64Encoding = nil then
begin
LEncoding := TBase64Encoding.Create;
if AtomicCmpExchange(Pointer(FBase64Encoding), Pointer(LEncoding), nil) <> nil then
LEncoding.Free;
{$IFDEF AUTOREFCOUNT}
FBase64Encoding.__ObjAddRef;
{$ENDIF AUTOREFCOUNT}
end;
Result := FBase64Encoding;
end;
I think it must be written as:
class function TNetEncoding.GetBase64Encoding: TNetEncoding;
var
LEncoding: TBase64Encoding;
begin
if FBase64Encoding = nil then
begin
LEncoding := TBase64Encoding.Create;
if AtomicCmpExchange(Pointer(FBase64Encoding), Pointer(LEncoding), nil) <> nil then
LEncoding.Free
{$IFDEF AUTOREFCOUNT}
!!!ELSE!!! FBase64Encoding.__ObjAddRef;
{$ENDIF AUTOREFCOUNT}
end;
Result := FBase64Encoding;
end;
Am I wrong?
To find a memory leak, look at how much RAM the system is using. The Resource Monitor in Windows can be used to accomplish this. In Windows 8.1 and Windows 10: To open the Run dialogue, press Windows+R, then type "resmon" and click OK.
Where are memory leaks found? Explanation: Memory leaks happen when your code needs to consume memory in your application, which should be released after a given task is completed but isn't. Memory leaks occur when we are developing client-side reusable scripting objects.
The reality is that memory leaks can strike any application in any language. They're more common in older or “closer to the metal” languages like C or C++, sure. But all it takes is a visit to one poorly-optimized web page to discover that even a language like JavaScript can have problems with memory leaks.
You are correct. The code fails when the if statement evaluates true. When that happens another thread has managed to assign the singleton first, and already increased the ref count. The ref count should not be increased again.
You should submit a bug report.
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