Bad_alloc没有在我期望的时候抛出
Bad_alloc not thrown when I expect it to
考虑这个简单的程序:
#include <exception>
#include <iostream>
int main(void)
{
const std::size_t size = 1<<31;
int *a = NULL;
try
{
a = new int[size];
}
catch (std::exception &e)
{
std::cerr << "caught some bad guy" << std::endl;
return 1;
}
if (a == NULL)
{
std::cerr << "it's null, can't touch this" << std::endl;
return 1;
}
std::cerr << "looks like 'a' is allocated alright!" << std::endl;
for (size_t i = 0; i < size; i ++)
std::cout << a[i] << " ";
return 0;
}
论>- 我尝试分配一些荒谬的内存量:
(1<<31) * sizeof(int)
== 8GB - 我增加了安全检查
- 捕获
std::exception
,在其他例外情况下应该捕获std::bad_alloc
… - 检查它是否不为空(即使这个检查实际上是有意义的,我需要
a = new (std::nothrow) int[size]
-但不管我如何分配内存,它不起作用)
- 捕获
- RAM安装:2GB
- 操作系统:Debian
- 架构:32位
问题是程序没有提前退出,而是这样做:
rr-@burza:~$ g++ test.cpp -o test && ./test
looks like 'a' is allocated alright!
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
(...many other zeros here...)
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0Segmentation fault
打印的零的数目正好是33790,这告诉我确切的…什么都没有。我怎样才能使我的程序防分段故障?
这似乎是您的环境中的一个错误,导致new[]
实现中的整数溢出。实际上,您分配了0个字节。可能是这个虫子。c++ 03标准没有明确应该发生什么,在c++ 11中应该抛出std::bad_array_new_length
。
如果您需要支持此系统,您可以在分配之前检查是否有溢出的机会,例如:
size_t size_t_max = -1;
if (size > size_t_max / sizeof(int))
throw ...;
如果你使用的库没有这样的检查(例如std::vector
的实现),这个错误可能仍然会影响你。
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 从构造函数抛出异常时如何克服内存泄漏
- GCC对可能有效的代码抛出init list生存期警告
- 如何在文件和行号中抛出错误
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- cmath抛出错误C2062、C2059、C2143和C2447.cmath包含在矢量文件中
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- Vulkan验证层不断在VkQueuePresentKHR()上抛出图像布局错误
- 如何通过参数抛出错误消息
- 函数如何通知用户它基于函数原型抛出异常?
- 为什么 boost::interprocess::managed_shared_memory 在施工时会抛出 boost
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- 编译器错误:destuctor 的更宽松的抛出说明符
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- CppSQLite 抛出"LNK2019: unresolved external symbol"错误
- 精神X3不抛出期望失败
- 避免在期望解析器失败时抛出expectation_failure
- Bad_alloc没有在我期望的时候抛出