内存泄漏能走多远?

2021-12-31 00:00:00 memory c memory-leaks c++

我多次遇到内存泄漏.通常当我 malloc-ing 就像没有明天,或者像脏衣服一样晃动 FILE * 时.我通常假设(阅读:绝望地希望)至少在程序终止时清除所有内存.是否存在程序终止或崩溃时不会收集泄漏内存的情况?

I've run into memory leaks many times. Usually when I'm malloc-ing like there's no tomorrow, or dangling FILE *s like dirty laundry. I generally assume (read: hope desperately) that all memory is cleaned up at least when the program terminates. Are there any situations where leaked memory won't be collected when the program terminates, or crashes?

如果答案因语言而异,那么让我们关注 C(++).

If the answer varies widely from language-to-language, then let's focus on C(++).

请注意短语就像没有明天"和摇晃……就像脏衣服"的双曲线用法.不安全* malloc*ing 会伤害你所爱的人.此外,请小心处理脏衣服.

Please note hyperbolic usage of the phrase, 'like there's no tomorrow', and 'dangling ... like dirty laundry'. Unsafe* malloc*ing can hurt the ones you love. Also, please use caution with dirty laundry.

推荐答案

没有.操作系统在进程退出时释放进程持有的所有资源.

No. Operating systems free all resources held by processes when they exit.

这适用于操作系统维护的所有资源:内存、打开的文件、网络连接、窗口句柄...

This applies to all resources the operating system maintains: memory, open files, network connections, window handles...

也就是说,如果程序在没有操作系统的嵌入式系统上运行,或者使用非常简单或有问题的操作系统,则内存可能无法使用,直到重新启动.但如果你处于那种情况,你可能就不会问这个问题了.

That said, if the program is running on an embedded system without an operating system, or with a very simple or buggy operating system, the memory might be unusable until a reboot. But if you were in that situation you probably wouldn't be asking this question.

操作系统可能需要很长时间才能释放某些资源.例如,网络服务器用于接受连接的 TCP 端口可能需要几分钟才能变为空闲状态,即使被程序正确关闭也是如此.联网程序还可以拥有远程资源,例如数据库对象.当网络连接丢失时,远程系统应该释放这些资源,但它可能比本地操作系统需要更长的时间.

The operating system may take a long time to free certain resources. For example the TCP port that a network server uses to accept connections may take minutes to become free, even if properly closed by the program. A networked program may also hold remote resources such as database objects. The remote system should free those resources when the network connection is lost, but it may take even longer than the local operating system.

相关文章