加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 无法在MinGW中捕获bad_alloc

发布时间:2020-12-16 07:02:45 所属栏目:百科 来源:网络整理
导读:我正在为一个家庭作业编写一个程序,我需要分配许多对象来检查局部性和性能等等.我似乎无法捕捉到新的抛出的异常 #include "List.h"#includeiostream#include exceptionint main(int argc,char **argv) { cout "size of List c++ : " sizeof(List) endl; //16
我正在为一个家庭作业编写一个程序,我需要分配许多对象来检查局部性和性能等等.我似乎无法捕捉到新的抛出的异常

#include "List.h"
#include<iostream>
#include <exception>

int main(int argc,char **argv) {
    cout << "size of List c++ : " << sizeof(List) << endl;  //16
    List * ptrList = new List();
    unsigned long var = 0;
    try {
        for (;; ++var) {
            List * ptrList2 = new  List();
            ptrList->next = ptrList2;
            ptrList2->previous = ptrList;
            ptrList = ptrList2;
        }
    } catch (bad_alloc const& e) {
        cout << "caught : " << e.what() << endl;
//  } catch (...) { //this won't work either
    }

结果是 :

This application has requested the Runtime to terminate it in an
unusual way. Please contact the application’s support team for more
information.

如果我将分配部分更改为:

List * ptrList2 = new (nothrow) List();
            if (!ptrList2) {
                cout << "out of memory - created " << var << " nodes" << endl;
                break;
            }

我很高兴:

out of memory - created 87921929 nodes

为什么我不能抓住bad_alloc?

我在Windows 7 x64 Pro上使用mingwin

C:UsersMrD>g++ --version
g++ (GCC) 4.7.2

列表 :

class List {
    long j;
public:
    List * next;
    List * previous;
    virtual long jj() {
        return this->j;
    }
    List() {
        next = previous = 0;
        j = 0;
    }
    virtual ~List() {
        if (next) {
            next->previous = this->previous;
        }
        if (previous) {
            previous->next = this->next;
        }
    }
};

解决方法

因为没有人自愿参加 I did it – 尤其是George Koehler对于某些gdb调试的回答 – 看来它毕竟是一个bug但我不会接受我的回答,直到这被证实 – 厌倦了等待.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读