malloc in C++: Usage and Best Practices

In C++, the new keyword is commonly used to dynamically allocate memory instead of using the malloc function. The malloc function is a function used in C language for dynamic memory allocation, with the following usage:

#include <stdlib.h> // 包含malloc函数的头文件

int main() {
    int *ptr;
    ptr = (int*)malloc(5 * sizeof(int)); // 分配5个int大小的内存空间
    if (ptr == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    
    // 使用ptr指向的内存空间
    for (int i = 0; i < 5; i++) {
        ptr[i] = i;
    }
    
    // 释放内存
    free(ptr);
    
    return 0;
}

It is important to note that memory allocated with the malloc function needs to be manually released, otherwise it can lead to memory leaks. Therefore, in C++, it is recommended to use the new and delete keywords for dynamic memory allocation and deallocation.

bannerAds