Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

So sánh malloc() và new() trong C/C++

malloc() – C style

Cấp phát bộ nhớ thô (raw bytes), không khởi tạo. Trả về void* (cần ép kiểu). Trả về NULL nếu thất bại. Khai báo trong <stdlib.h>.

ptr = (type*)malloc(size_in_bytes);

Ví dụ

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 4, *p, sum = 0;
    p = (int*)malloc(n * sizeof(int));
    if (!p) { printf("Loi cap phat"); return 1; }
    
    for (int i = 0; i < n; i++) {
        scanf("%d", p + i);
        sum += p[i];
    }
    printf("Tong: %d", sum);
    free(p);
    return 0;
}

new – C++ style

Toán tử new cấp phát trong heap, gọi constructor, trả về con trỏ đúng kiểu (type-safe). Ném exception std::bad_alloc nếu thất bại (hoặc std::nothrow trả về NULL).

Cú pháp

Type *ptr = new Type;           // 1 object, default init
Type *ptr = new Type(value);    // 1 object, init value
Type *ptr = new Type[n];        // Array n objects

Ví dụ

#include <iostream>
#include <new>
using namespace std;

int main() {
    int *p1 = new int;           // 1 int, uninitialized
    *p1 = 28;
    
    float *p2 = new float(223.324f); // 1 float, init
    
    int *p3 = new int[28];       // Array 28 int
    if (!p3) { cout << "Failed"; return 1; }
    
    for (int i = 10; i < 15; i++) p3[i] = i + 1;
    for (int i = 10; i < 15; i++) cout << p3[i] << " ";
    
    delete p1;
    delete p2;
    delete[] p3;  // Quan trong: delete[] cho array
    return 0;
}

Kết quả

11 12 13 14 15

Bảng so sánh chi tiết

Đặc điểmmalloc/freenew/delete
Ngôn ngữC/C++Chỉ C++
Khởi tạo objectKhông (raw memory)Có (gọi constructor)
Hủy objectKhông (chỉ free memory)Có (gọi destructor)
Type safetyCần ép kiểu (void*)Tự động kiểu đúng
Thất bạiTrả về NULLNém bad_alloc
Resizerealloc()Không có (phải new+copy+delete)
OverloadKhôngCó (class/::operator new)
Array deletefree()delete[] (bắt buộc)

Khuyên dùng: C++ code dùng new/delete (hoặc smart pointer unique_ptr, vector). C code dùng malloc/free. Không trộn lẫn.