如何在 Delphi 中泄漏字符串 [英] How to leak a string in Delphi

查看:13
本文介绍了如何在 Delphi 中泄漏字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天我正在和一位同事谈论如果你真的把事情搞砸了,你如何在 Delphi 中泄漏字符串.默认情况下,字符串是引用计数并自动分配的,因此它们通常无需任何考虑即可工作 - 无需手动分配、大小计算或内存管理.

I was talking to a co-worker the other day about how you can leak a string in Delphi if you really mess things up. By default strings are reference counted and automatically allocated, so they typically just work without any thought - no need for manual allocation, size calculations, or memory management.

但我记得有一次读到有一种方法可以直接泄漏字符串(而不将其包含在泄漏的对象中).它似乎与通过引用传递字符串,然后从它传递到的例程中的更大范围访问它有关.是的,我知道这很模糊,这就是我在这里问这个问题的原因.

But I remember reading once that there is a way to leak a string directly (without including it in an object that gets leaked). It seems like it had something to do with passing a string by reference and then accessing it from a larger scope from within the routine it was passed to. Yeah, I know that is vague, which is why I am asking the question here.

推荐答案

我不知道你第二段中的问题,但我被记录中泄露的字符串咬了一口.

I don't know about the issue in your second paragraph, but I was bitten once by leaked strings in a record.

如果在包含字符串的记录上调用 FillChar(),则会用零覆盖引用计数和动态分配的内存地址.除非字符串为空,否则这将泄漏内存.解决这个问题的方法是在清除记录占用的内存之前调用记录上的 Finalize().

If you call FillChar() on a record that contains strings you overwrite the ref count and the address of the dynamically allocated memory with zeroes. Unless the string is empty this will leak the memory. The way around this is to call Finalize() on the record before clearing the memory it occupies.

不幸的是,当没有需要终结的记录成员时调用 Finalize() 会导致编译器提示.我碰巧注释掉了 Finalize() 调用以使提示静音,但后来当我向记录中添加一个字符串成员时,我错过了取消对调用的注释,因此引入了泄漏.幸运的是,我通常在调试模式下最冗长和偏执的设置中使用 FastMM 内存管理器,所以泄漏没有被忽视.

Unfortunately calling Finalize() when there are no record members that need finalizing causes a compiler hint. It happened to me that I commented out the Finalize() call to silence the hint, but later when I added a string member to the record I missed uncommenting the call, so a leak was introduced. Luckily I'm generally using the FastMM memory manager in the most verbose and paranoid setting in debug mode, so the leak didn't go unnoticed.

编译器提示可能不是什么好事,如果不需要的话,默默地省略 Finalize() 调用会好得多恕我直言.

The compiler hint is probably not such a good thing, silently omitting the Finalize() call if it's not needed would be much better IMHO.

这篇关于如何在 Delphi 中泄漏字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆