面试题答案
一键面试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;
}
new
- 常规处理方式:在C++中,使用
new
分配内存失败时,默认情况下会抛出std::bad_alloc
异常。程序可以通过try - catch
块来捕获并处理这个异常。 - 示例:
- 常规处理方式:在C++中,使用
#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;
}