在调用 FreeMem 之前检查内存是否已分配(Delphi 32)

发布于 2024-09-09 07:35:21 字数 237 浏览 7 评论 0原文

我遇到过错误,对象以某种方式被释放,但我们最终对它们调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黯然#的苍凉 2024-09-16 07:35:21

与 FreeAndNil 等价的只是

FreeMem(p);
p := nil;

但是你可以通过找到释放后使用的对象来更好地解决真正的问题。尝试 FastMM - 它将帮助您完成该任务。

The equivalent to FreeAndNil would just be

FreeMem(p);
p := nil;

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.

终陌 2024-09-16 07:35:21

无论如何,您都不应该在对象上调用 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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文