gpt4 book ai didi

delphi - FastMM 报告记录线程变量内存泄漏

转载 作者:行者123 更新时间:2023-12-02 21:05:52 27 4
gpt4 key购买 nike

FastMM 报告以下使用带有字符串的记录线程变量的代码片段存在内存泄漏 (UnicodeString):

program Project10;

{$APPTYPE CONSOLE}

{$R *.res}

uses
FastMM4,
System.SysUtils;

type
TContext = record
Value : String;
end;

threadvar
Context : TContext;

begin
Context.Value := 'asdfsdfasfdsa';
end.

这是真正的内存泄漏还是在 FastMM 检查内存泄漏后才发生线程变量的清理?

更重要的是:如何抑制这些“内存泄漏”的报告,因为它们会混淆可能发现的任何其他内存泄漏?

最佳答案

这确实是一次泄漏。线程局部变量超出范围时不会被最终确定。因为您的记录包含一个受管理的字段(字符串字段),所以如果记录未最终确定,则与该字符串关联的堆分配内存将被泄漏。

documentation明确指出这一点:

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.

如果您想堵塞泄漏,您需要在作用域结束时完成变量。也就是说,当线程终止时。

Finalize(Context);

请注意,您必须从拥有该变量的线程执行此代码,因为显然只有该线程才能访问它。

如果您想禁止报告这些泄漏,请调用 RegisterExpectedMemoryLeak。

如果线程终止时无法执行代码,那么最好避免堆分配并使用固定长度的字符数组。您很可能满足您的需求。

您声称线程终止时无法执行代码,这似乎很奇怪。如果您不能做到这一点,您如何能够在这些线程的上下文中执行任何代码。换句话说,为了发生泄漏,您必须在这些线程中执行代码。

关于delphi - FastMM 报告记录线程变量内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com