C++ Malloc Failure Detection
In C++, the malloc function is defined as void* malloc(size_t size);, it will try to allocate memory of the specified size and return a pointer to that memory block. If malloc fails to allocate memory, it will return nullptr. Therefore, we can determine if memory allocation has failed by checking if the return value of malloc is nullptr. Here is an example code:
#include <iostream>
#include <cstdlib>
int main() {
int size = 100;
int* ptr = (int*)malloc(size * sizeof(int));
if (ptr == nullptr) {
std::cout << "Memory allocation failed" << std::endl;
} else {
std::cout << "Memory allocation successful" << std::endl;
// 使用分配的内存
free(ptr);
}
return 0;
}