扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c++中malloc运算符如何判断失败

扬州沐宇科技
2024-02-18 10:19:13
c++

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

#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;
}

扫码添加客服微信