【问题标题】:Can't catch bad_alloc in MinGW无法在 MinGW 中捕获 bad_alloc
【发布时间】:2012-12-13 00:48:06
【问题描述】:

我正在为家庭作业编写一个程序,我需要分配许多对象来检查位置和性能等方面的内容。我似乎无法捕捉到new 引发的异常

#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
    }

结果:

此应用程序已请求运行时终止它 不寻常的方式。请联系应用程序的支持团队了解更多信息 信息。

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

            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:\Users\MrD>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;
        }
    }
};

【问题讨论】:

  • 您可能没有足够的内存来处理异常。
  • @Chris:Wow - 从来没有想过 :) - 任何方式来告诉(虽然似乎很荒谬 - bad_alloc 抛出 bad_alloc ?)
  • 我不确定。我之所以想到这一点,是因为我几天前在“为什么使用 nothrow 版本?”中看到了它。问题。
  • en.cppreference.com/w/cpp/memory/new/set_new_handler,试试那里的例子。你也可以尝试在启动时分配一个缓冲区,然后在 new-handler 中释放它(并抛出),看看是否可能需要异常处理。
  • @Chris:我认为这不太可能。它通常被抛出并分配在堆栈上。

标签: c++ exception g++ mingw try-catch


【解决方案1】:

由于没有人自愿 I did it - 尤其是 George Koehler 对一些 gdb 调试的回答 - 毕竟这似乎是一个错误,但 在得到验证之前我不会接受我的回答 - 厌倦了等待。

【讨论】:

  • 我在使用 -Wl,--wrap,malloc 包装 malloc 时也看到了这一点。如果我在尝试分配字符串时模拟失败(仅针对单个 malloc),这会给我一个 sigsegv 而不是抛出 std::bad_alloc 异常。不知道为什么。
猜你喜欢
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2018-12-28
  • 2020-09-06
  • 1970-01-01
相关资源
最近更新 更多