我期望它不会抛出Bad_alloc

 dyh81216462 发布于 2023-01-18 11:08

考虑这个简单的程序:

#include 
#include 

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,这正好告诉我......什么都没有.如何使我的程序具有段错误?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有