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ểm | calloc | malloc |
|---|---|---|
| Khởi tạo 0 | Có | Không (rác) |
| Tham số | (num, size) | (total_bytes) |
| Overflow check | Tự động (num*size) | Phải tự kiểm tra |
| Hiệu năng | Chậm hơn (zero-fill) | Nhanh hơn |
| Dùng khi | Cần mảng khởi tạo 0 | Sẽ 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.