开发者

Using FastMM4, how to register leaked string?

开发者 https://www.devze.com 2023-03-05 14:44 出处:网络
With FastMM4 one can easily register a leaked pointer, but not a leaked string. Apparently the @ operator applied to a string is not really giving us the whole string, nor is PChar(string); What can I

With FastMM4 one can easily register a leaked pointer, but not a leaked string. Apparently the @ operator applied to a string is not really giving us the whole string, nor is PChar(string); What can I use to nicely register a leaked string?

For now I found this works:

FastMM4.RegisterExpectedMemoryLeak(Pointer(NativeInt(PChar(StringVariable))-12));

But it relies on the magic number 12, and that's version-dependent, and the code really doesn't express what's going on. I hope there's a RTL function somewhere that takes a string and gives back a pointer to the "base" of the string, or some FastMM4 method that I overlooked.

I can pack that ugly beast of expression in a procedure like this, but I still find it hacky:

procedure RegisterExpectedStringLeak(const s:string);
begin
  {$IFDEF VER210}
  FastMM4.RegisterExpectedMemoryLeak(Pointer(NativeInt(PChar(s))-12));
  {$ELSE}
  {$MESSAGE Fatal 'This only works on Delphi 2010'}
  {$ENDIF}
end;

This should be irrelevant for the question. Here's why I'm leaking strings:

I'm using a caching mechanism to store certain pieces of data for the life of the application. I do not intend to free those objects, because I do nee开发者_如何学God them for the life of the application and going through proper finalization only waists time at application shutdown. Those objects contain some string fields, so obviously those strings are "leaked".


The closest I can think of would be:

function RegisterExpectedStringLeak(const S: string): Boolean;
  type
    {Have to redeclare StrRec here, because it is not in the interface section of system.pas}
    PStrRec = ^StrRec;
    StrRec = packed record
      {$ifdef CONDITIONALEXPRESSIONS}
      {$if RTLVersion >= 20}
      codePage: Word;
      elemSize: Word;
      {$ifend}
      {$endif}
      refCnt: Longint;
      length: Longint;
    end;
begin
  Result := RegisterExpectedMemoryLeak(Pointer(NativeInt(PChar(S)) - SizeOf(StrRec)));
end;

The re-declaration of StrRec is copied from Delphi XE's getmem.inc (FastMM4) - I only added the {$ifdef CONDITIONALEXPRESSIONS}. I think it should be backwards-compatible with older versions of Delphi, too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号