Using FastMM4, how to register leaked string?

感情迁移 提交于 2019-12-13 01:03:08

问题


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 need 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".


回答1:


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.



来源:https://stackoverflow.com/questions/5963001/using-fastmm4-how-to-register-leaked-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!