在调用 FreeMem 之前检查内存是否已分配(Delphi 32)
我遇到过错误,对象以某种方式被释放,但我们最终对它们调用 FreeMem。当然,这会导致错误,因为内存已经被释放并抛出错误。
我知道 try-catch 块可能会修复它,但这是很多 try-catch 块。使用常规 object.free 避免这种情况的方法是 FreeAndNil(object) 但我找不到 FreeMem 的等效项。在释放之前测试它是否已分配的东西。
在易于阅读、可维护性和稳定性方面最好的解决方案是什么?
I have been running into errors where objects are somehow freed but we end up calling FreeMem on them. Of course this causes an error since the memory has already been freed and throws an error.
I know that a try-catch block would probably fix it but that's a lot of try-catch blocks. With the regular object.free the way to avoid this is FreeAndNil(object) but I can't find the equivalent for FreeMem. Something which tests whether it's allocated or not before freeing.
What's the best solution here in ease of reading, maintainability, and stability.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与 FreeAndNil 等价的只是
但是你可以通过找到释放后使用的对象来更好地解决真正的问题。尝试 FastMM - 它将帮助您完成该任务。
The equivalent to FreeAndNil would just be
But you'll better fix the real problem by finding which object you use after it's freed. Try FastMM - it will help you with that task.
无论如何,您都不应该在对象上调用 FreeMem。它需要通过其析构函数调用 Free 来销毁。但是,如果您正在使用指向其他事物(例如记录)的指针,那么就按照乌尔里希所说的那样。 (它的两个部分。)
You shouldn't be calling FreeMem on an object anyway. It needs to be destroyed with its destructor, by calling Free on it. But if you're working with pointers to other things (records, for example,) then go with what Ulrich said. (Both parts of it.)