C++でのmalloc演算子の失敗判定方法は何ですか?

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