我在这里造成内存泄漏吗?
一个非常简单的问题:
type
TMyRecord = Record
Int: Integer;
Str: String;
end;
PMyRecord = ^TMyRecord;
var
Data: PMyRecord;
begin
New(Data);
Data.Int := 42;
Data.Str := 'Test';
Dispose(Data);
end;
我的问题是,我是否在这里造成内存泄漏(使用 String
)?我应该在调用 Dispose
之前调用 Data.Str := '';
吗?
谢谢!
A very simple question:
type
TMyRecord = Record
Int: Integer;
Str: String;
end;
PMyRecord = ^TMyRecord;
var
Data: PMyRecord;
begin
New(Data);
Data.Int := 42;
Data.Str := 'Test';
Dispose(Data);
end;
My question is, am I creating a memory leak here (with the String
)? Should I call Data.Str := '';
before calling Dispose
?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,
Dispose
可以正确释放记录中的字符串和动态数组,包括嵌套的数组。GetMem
/FreeMem(Data)
确实会造成内存泄漏。No,
Dispose
properly frees strings and dynamic arrays in records, including nested ones.GetMem
/FreeMem(Data)
would create a memory leak, indeed.如果在分配/释放对之间引发异常,则表示内存泄漏。像这样保护它们是正常的:
It's a memory leak if an exception is raised in between your allocate/deallocate pairs. It is normal to protect them as such:
不,你不是,字符串在被删除时会自行清理自己的内存。
No you are not, String cleans its own memory itself when it is deleted.
如果你想要内存泄漏,据我所知,你必须使用 TP 对象:-) 它们是 Delphi 中唯一未初始化/最终化的结构化类型
If you want a memory leak, afaik you have to use TP objects :-) They are afaik the only structured types in Delphi that are not initialized/finalized