相关疑难解决方法(0)

函数不会抛出bad_alloc异常

我正在尝试从Stroustrup的C++ PL4书中做一个练习.任务是:

使用分配这么多的内存newbad_alloc被抛出.报告分配了多少内存以及花费了多少时间.这样做两次:一次不写入分配的内存,一次写入每个元素.

以下代码不会引发std::bad_alloc异常.执行程序后,我在终端收到消息"Killed".

也.以下代码在~4秒内退出.但是当我取消注释内存使用消息时

// ++i;
// std::cout << "Allocated " << i*80 << " MB so far\n";
Run Code Online (Sandbox Code Playgroud)

程序将运行几分钟.经过一段时间后,它打印出已经分配了数TB的内存,但我没有看到System Monitor应用程序发生太大变化.这是为什么?

我使用Linux和System Monitor应用程序查看用法.

#include <iostream>
#include <vector>
#include <chrono>

void f()
{
    std::vector<int*> vpi {};
    int i {};
    try{
        for(;;){
            int* pi = new int[10000];
            vpi.push_back(pi);
            // ++i;
            // std::cout << "Allocated " << i*80 << " MB so far\n";
        }       
    }
    catch(std::bad_alloc){
        std::cerr << "Memory exhausted\n";
    }
}

int main() {
    auto t0 …
Run Code Online (Sandbox Code Playgroud)

c++ exception out-of-memory bad-alloc

5
推荐指数
1
解决办法
512
查看次数

标签 统计

bad-alloc ×1

c++ ×1

exception ×1

out-of-memory ×1