开发者

Checking if memory is allocated before calling FreeMem (Delphi 32)

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 probab开发者_运维知识库ly 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.


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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜