假设我有这样的功能:
int main()
{
char* str = new char[10];
for(int i=0;i<5;i++)
{
//Do stuff with str
}
delete[] str;
return 0;
}
如果我要结束程序,为什么我需要删除
str
? 如果我只是要退出,我不会在乎那个内存是否会进入一个充满 unicorn 的土地,对吧?这只是一种好的做法吗?
它有更深层次的后果吗?
最佳答案
如果事实上你的问题是“我有这个琐碎的程序,我可以在它退出之前不释放几个字节吗?”答案是肯定的,没关系。在任何现代操作系统上都可以。而且程序很简单;这不像你要把它放进心脏起搏器或用这个东西运行丰田凯美瑞的制动系统。如果唯一的客户是你,那么你唯一可能会因为马虎而影响的人就是你。
当你开始从这个关于平凡案例的问题的答案中概括到不平凡的案例时,问题就出现了。
因此,让我们就一些不平凡的案例提出两个问题。
I have a long-running service that allocates and deallocates memory in complex ways, perhaps involving multiple allocators hitting multiple heaps. Shutting down my service in the normal mode is a complicated and time-consuming process that involves ensuring that external state -- files, databases, etc -- are consistently shut down. Should I ensure that every byte of memory that I allocated is deallocated before I shut down?
是的,我会告诉你原因。长时间运行的服务可能发生的最糟糕的事情之一是它意外泄漏内存。随着时间的推移,即使是微小的泄漏也会导致巨大的泄漏。查找和修复内存泄漏的标准技术是检测分配堆,以便在关闭时记录所有已分配但未被释放的资源。除非您喜欢追踪大量误报并在调试器中花费大量时间,否则始终释放您的内存,即使严格来说没有必要这样做。
用户已经预计关闭服务可能需要数十亿纳秒,所以谁在乎你是否会对虚拟分配器造成一点额外压力以确保一切都得到清理?这只是您为大型复杂软件支付的价格。而且你并不是一直在关闭服务,所以再一次,谁在乎它是否比它可能慢了几毫秒?
I have that same long-running service. If I detect that one of my internal data structures is corrupt I wish to "fail fast". The program is in an undefined state, it is likely running with elevated privileges, and I am going to assume that if I detect corrupted state, it is because my service is actively being attacked by hostile parties. The safest thing to do is to shut down the service immediately. I would rather allow the attackers to deny service to the clients than to risk the service staying up and compromising my users' data further. In this emergency shutdown scenario should I make sure that every byte of memory I allocated is freed?
当然不是。操作系统会为您解决这个问题。如果您的堆损坏,则攻击者可能希望您释放内存作为他们攻击的一部分。每毫秒都很重要。在你将战术核武器扔到建筑物上之前,你为什么还要费心擦亮门 Handlebars 和擦厨房呢?
所以“我应该在程序退出之前释放内存吗?”这个问题的答案。是“这取决于你的程序做什么”。
关于c++ - 为什么我需要删除[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488099/