在C++中,malloc
函数被定义为 void* malloc (size_t size);
,它会尝试分配指定大小的内存,并返回一个指向该内存块的指针。如果 malloc
分配内存失败,则返回 nullptr
。因此,可以通过检查 malloc
的返回值是否为 nullptr
来判断内存分配是否失败。以下是一个示例代码:
#include#include 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; }