Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 thread 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?

like image 656
mj2008 Avatar asked Mar 28 '11 08:03

mj2008


1 Answers

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.
like image 66
David Heffernan Avatar answered Dec 21 '22 13:12

David Heffernan