zoukankan      html  css  js  c++  java
  • 内存分配失败错误处理

    一、C语言中的malloc/calloc/realloc/valloc/alloca/memalign函数:

    这样的内存分配函数在内存分配失败时都返回空指针因此在调用返回时检查返回值的方法比较简单只需要与空指针比较即可

    :

    char* p = (char*)malloc(1204)

    if(p == NULL)

    {

    //error handle

    }

    char* pp = (char*)calloc(31024)

    if(pp == NULL)

    {

    //error handle

    }

    二、C++中的new操作符:

    C++中的new操作符在分配内存失败时默认的操作是抛出一个内置的异常而并不是直接返回空指针这样的话再把返回值与空指针比较就没有什么意义了因为C++抛出异常之后就直接跳出new操作符所在的那一行代码而不再执行后续的代码行了所以对new操作符返回值的判断代码就执行不到了当然标准C++也提供了抑制抛出异常的方法使之不再排除内存分配失败的异常转而直接返回空指针这是因为比较古老的编译器里面可能没有异常处理机制不能捕获到异常:

    int* p = new int[SIZE]

    if(p == 0) //检查p是否是空指针这个判断没有意义

    {

    return -1

    }

    所以在C++中有两种方法来处理new操作符分配内存失败的错误

    1、通过捕获new操作符抛出的异常:

    char* p = NULL

    try

    {

    p = new char[1024]

    }

    catch(const std::bad_alloc& ex)

    {

    //exception handle

    return -1

    }

    2、抑制异常的抛出:

    char* p = NULL

    p = new(std::nothrow)char[1024] //这样的话如果new分配内存失败就不会再抛出异常而是返回空指针了

    if(p == NULL)                    //这样的判断就有意义了

    {

    //error handle

    return -1

    }

    原文:

    http://blog.csdn.net/app_12062011/article/details/7302673

  • 相关阅读:
    背水一战 Windows 10 (90)
    背水一战 Windows 10 (89)
    背水一战 Windows 10 (88)
    背水一战 Windows 10 (87)
    背水一战 Windows 10 (86)
    背水一战 Windows 10 (85)
    背水一战 Windows 10 (84)
    背水一战 Windows 10 (83)
    背水一战 Windows 10 (82)
    背水一战 Windows 10 (81)
  • 原文地址:https://www.cnblogs.com/mydomain/p/3001098.html
Copyright © 2011-2022 走看看