声明struct表时std :: bad_alloc错误

时间:2011-10-21 15:41:59

标签: c++ c

我宣布了简单的结构:

struct Heap {
  int size;
  int *heap_array;
};

当我试图创建表时,其中k是来自stdin的int:

Heap *rooms = new Heap[k];

我得到了:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

使用int字面意思一切正常:

Heap *rooms = new Heap[0];

如何声明这样的表?

1 个答案:

答案 0 :(得分:5)

有可能从stdin读取的值无效。如果读取失败,您可能会有一些默认值,如2 ^ 32。

相关问题