开发者

How to finalise a threadvar string to prevent a leak?

This is not a major leak, but more of a would be nice to tidy I think, but I have found that my Delphi XE code can leak a String. This is because it is defined as a threadvar as it needs to be, but when the thre开发者_开发技巧ad terminates, it is apparently not tidying up such variables.

Is there a way for me to manually tidy a string on termination of the thread? Do I just assign an empty string to it, or set it to nil or something?


Assign an empty string to it, set it to nil or call Finalize() on it. They are all equivalent and they will deallocate the storage thus removing your memory leak.


In response to Marco's comment, the documentation is explicit on this:

Dynamic variables that are ordinarily managed by the compiler (long strings, wide strings, dynamic arrays, variants, and interfaces) can be declared with threadvar, but the compiler does not automatically free the heap-allocated memory created by each thread of execution. If you use these data types in thread variables, it is your responsibility to dispose of their memory from within the thread, before the thread terminates. For example:

threadvar
  S: AnsiString;

S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  ...
S := ;  // free the memory used by S

Rather bizarrely the documentation contains a clear error in the final line which should read S := nil;

It is of course easy to see for yourself that thread local variables are not disposed automatically:

program LeakMe;

{$APPTYPE CONSOLE}

threadvar
  s: string;

begin
  ReportMemoryLeaksOnShutdown := True;
  s := 'Leak me';
end.


Some other small solution - you can use ShortString instead of String here (or any other kind of fixed length array), then memory leak disappear

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜