C语言 - 动态内存分配

动态内存分配简介

在 C 语言里,动态内存分配允许程序在运行时请求和释放内存。这和在编译时就分配好固定大小内存的静态分配不同。动态内存分配主要通过标准库函数实现,如 `malloc`、`calloc`、`realloc` 和 `free`。

常用动态内存分配函数

1. `malloc` 函数

`malloc` 函数用于分配指定字节数的内存块。其原型如下:

void* malloc(size_t size);

示例代码:

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

int main() {
    int *ptr;
    // 分配 10 个 int 类型的内存空间
    ptr = (int*)malloc(10 * sizeof(int));
    if (ptr == NULL) {
        printf("内存分配失败\n");
        return 1;
    }
    // 使用分配的内存
    for (int i = 0; i < 10; i++) {
        ptr[i] = i;
    }
    // 输出分配内存中的值
    for (int i = 0; i < 10; i++) {
        printf("%d ", ptr[i]);
    }
    // 释放内存
    free(ptr);
    return 0;
}

2. `calloc` 函数

`calloc` 函数用于分配指定数量和大小的内存块,并将其初始化为 0。其原型如下:

void* calloc(size_t num, size_t size);

示例代码:

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

int main() {
    int *ptr;
    // 分配 10 个 int 类型的内存空间并初始化为 0
    ptr = (int*)calloc(10, sizeof(int));
    if (ptr == NULL) {
        printf("内存分配失败\n");
        return 1;
    }
    // 输出分配内存中的值
    for (int i = 0; i < 10; i++) {
        printf("%d ", ptr[i]);
    }
    // 释放内存
    free(ptr);
    return 0;
}

3. `realloc` 函数

`realloc` 函数用于调整已分配内存块的大小。其原型如下:

void* realloc(void* ptr, size_t size);

示例代码:

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

int main() {
    int *ptr;
    // 分配 10 个 int 类型的内存空间
    ptr = (int*)malloc(10 * sizeof(int));
    if (ptr == NULL) {
        printf("内存分配失败\n");
        return 1;
    }
    // 调整内存大小为 20 个 int 类型的空间
    ptr = (int*)realloc(ptr, 20 * sizeof(int));
    if (ptr == NULL) {
        printf("内存重新分配失败\n");
        return 1;
    }
    // 释放内存
    free(ptr);
    return 0;
}

4. `free` 函数

`free` 函数用于释放之前通过 `malloc`、`calloc` 或 `realloc` 分配的内存。其原型如下:

void free(void* ptr);

动态内存分配注意事项

回到课程目录