MST

星途 面试题库

面试题:C++中malloc和new内存分配失败处理的常规方式对比

在C++中,当使用malloc和new进行内存分配时,如果分配失败,它们各自的常规处理方式是什么?请分别阐述并举例说明。
39.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. malloc
    • 常规处理方式malloc分配内存失败时,会返回NULL。调用者需要检查返回值是否为NULL来判断内存分配是否成功。
    • 示例
#include <stdio.h>
#include <stdlib.h>

int main() {
    // 尝试分配1000000000000字节的内存(通常会失败)
    char* ptr = (char*)malloc(1000000000000);
    if (ptr == NULL) {
        printf("内存分配失败\n");
    } else {
        // 使用ptr
        free(ptr);
    }
    return 0;
}
  1. new
    • 常规处理方式:在C++中,使用new分配内存失败时,默认情况下会抛出std::bad_alloc异常。程序可以通过try - catch块来捕获并处理这个异常。
    • 示例
#include <iostream>
#include <new>

int main() {
    try {
        // 尝试分配1000000000000字节的内存(通常会失败)
        char* ptr = new char[1000000000000];
        // 使用ptr
        delete[] ptr;
    } catch (const std::bad_alloc& e) {
        std::cerr << "内存分配失败: " << e.what() << std::endl;
    }
    return 0;
}

另外,new还有一种不抛出异常的形式,即nothrow new,当这种形式分配内存失败时,会返回NULL,使用方式如下:

#include <iostream>
#include <new>

int main() {
    char* ptr = new (std::nothrow) char[1000000000000];
    if (ptr == NULL) {
        std::cerr << "内存分配失败" << std::endl;
    } else {
        // 使用ptr
        delete[] ptr;
    }
    return 0;
}