Khái niệm
malloc() (memory allocation) cấp phát một khối bộ nhớ động. Trả về con trỏ void trỏ đến vùng nhớ, hoặc NULL nếu thất bại. Vùng nhớ chứa giá trị rác.
Cú pháp
ptr = (cast_type*) malloc(kich_thuoc);
Ví dụ
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *MemoryAlloc;
MemoryAlloc = malloc(15 * sizeof(char));
if (MemoryAlloc == NULL) {
printf("Khong the cap phat bo nho\n");
} else {
strcpy(MemoryAlloc, "TutorialsPoint");
}
printf("Noi dung bo nho dong: %s\n", MemoryAlloc);
free(MemoryAlloc);
return 0;
}
Kết quả
Noi dung bo nho dong: TutorialsPoint