谁处理C ++“新”内存分配失败?

问题描述:

在C中,人们通常在使用malloc后检查空指针。但是,在C ++中,我们将使用new。我已经做了一些搜索,一个解释malloc和new之间的区别如下:
https://isocpp.org/wiki/faq/freestore-mgmt#new-malloc-diff

In C, people often check null pointers after using malloc. However, in C++, we will use "new". I have done some search and one explanation for the difference between malloc and new is below: https://isocpp.org/wiki/faq/freestore-mgmt#new-malloc-diff

从上面的链接报价:

malloc()通过返回0.通过抛出异常(bad_alloc)返回0.新报告分配和初始化错误来报告内存耗尽。

malloc() reports memory exhaustion by returning 0. new reports allocation and initialization errors by throwing exceptions (bad_alloc).

但是OS(Linux或Windows)如何对这个bad_alloc异常做出反应呢?

But how does OS (Linux or windows) react to this bad_alloc exception?

他们没有。操作系统不需要反应任何东西。您的程序可能会对该条件做出反应,或者可能会使该异常未处理并终止。无论如何,内存没有分配,操作系统不再关心,如果它关心(甚至知道它)在第一!

They don't. The OS doesn't need to "react" to anything. Your program might want to react to the condition, or it may leave the exception unhandled and terminate. Either way, the memory wasn't allocated and the OS doesn't care any more, if it cared (or even knew about it) in the first place!