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

So sánh calloc() và malloc() trong C

calloc()

Contiguous Allocation. Cấp phát nhiều block cùng kích thước, khởi tạo tất cả byte = 0.

void *calloc(size_t num, size_t size);

Tham số: num – số phần tử; size – kích thước mỗi phần tử. Trả về con trỏ hoặc NULL.

Ví dụ

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

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

Kết quả

Nhap 4 so: 2 24 35 12
Tong: 73

malloc()

Cấp phát bộ nhớ không khởi tạo (giá trị rác). Nhanh hơn calloc.

void *malloc(size_t size);

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; }
    
    printf("Nhap %d so: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", p + i);
        sum += p[i];
    }
    printf("Tong: %d", sum);
    free(p);
    return 0;
}

Kết quả

Nhap 4 so: 32 23 21 8
Tong: 84

Bảng so sánh

Đặc điểmcallocmalloc
Khởi tạo 0CóKhông (rác)
Tham số(num, size)(total_bytes)
Overflow checkTự động (num*size)Phải tự kiểm tra
Hiệu năngChậm hơn (zero-fill)Nhanh hơn
Dùng khiCần mảng khởi tạo 0Sẽ ghi đè ngay, cần tốc độ

Mẹo: calloc(n, size) an toàn hơn malloc(n * size) vì tránh tràn số khi tính n * size.