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

Cấp phát bộ nhớ động (Dynamic Memory Allocation) trong C

C cung cấp các hàm cấp phát/quản lý bộ nhớ trong <stdlib.h>:

Hàm Mô tả
void *calloc(int num, int size); Cấp phát mảng num phần tử, mỗi phần tử size byte.
void free(void *address); Giải phóng khối bộ nhớ tại address.
void *malloc(int num); Cấp phát num byte, không khởi tạo.
void *realloc(void *address, int newsize); Cấp phát lại, mở rộng đến newsize.

Cấp phát động

Nếu biết trước kích thước mảng, dễ dàng khai báo tĩnh. Ví dụ tên người tối đa 100 ký tự: char name[100].

Nhưng nếu không biết trước độ dài (ví dụ mô tả chi tiết), dùng con trỏ không khai báo kích thước, sau đó cấp phát theo yêu cầu.

Ví dụ malloc

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

int main() {
    char name[100];
    char *description;
    strcpy(name, "Adam");
    description = malloc(200 * sizeof(char));
    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcpy(description, "Adam a DPS student in class 10th");
    }
    printf("Name = %s\n", name);
    printf("Description: %s\n", description);
    return 0;
}

Kết quả

Name = Adam
Description: Adam a DPS student in class 10th

Dùng calloc() tương tự: calloc(200, sizeof(char)). Kiểm soát hoàn toàn kích thước, khác mảng tĩnh không thể thay đổi size.

Thay đổi kích thước (realloc)

Khi không cần bộ nhớ, nên gọi free(). Hoặc tăng/giảm size bằng realloc().

Ví dụ realloc & free

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

int main() {
    char name[100];
    char *description;
    strcpy(name, "Adam");
    description = malloc(30 * sizeof(char));
    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcpy(description, "Adam a DPS student.");
    }
    // Cần lưu mô tả lớn hơn
    description = realloc(description, 100 * sizeof(char));
    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcat(description, "He is in class 10th");
    }
    printf("Name = %s\n", name);
    printf("Description: %s\n", description);
    free(description);
    return 0;
}

Kết quả

Name = Adam
Description: Adam a DPS student.He is in class 10th

Nếu không realloc, strcat() sẽ lỗi do thiếu bộ nhớ.