Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ARC: is there a memory leak in TNetEncoding.GetBase64Encoding?

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?

like image 597
zeus Avatar asked Jan 20 '18 14:01

zeus


People also ask

How do you check if there are memory leaks?

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?

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.

Do all programs have memory leaks?

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.


1 Answers

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.

like image 116
David Heffernan Avatar answered Oct 24 '22 05:10

David Heffernan