ZetCode

C malloc 和 free 教程

最后修改于 2024 年 1 月 29 日

C 语言中的动态内存分配是一项强大的功能,它允许程序在运行时分配内存。malloc 函数用于分配内存,而 free 函数用于释放内存。本教程涵盖了 mallocfree 的基础知识、用法以及实际示例。

malloc 和 free 是什么?

malloc 函数用于分配指定大小的内存块,并返回指向该内存块开头的指针。free 函数用于释放先前由 malloc 分配的内存,使其可用于将来的分配。正确使用这些函数对于避免内存泄漏和未定义行为至关重要。

基本内存分配

本示例演示了如何使用 mallocfree 来分配和释放内存。

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

int main() {
    int *ptr;
    ptr = (int *)malloc(5 * sizeof(int));  // Allocate memory for 5 integers

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;  // Assign values to the allocated memory
    }

    for (int i = 0; i < 5; i++) {
        printf("%d ", ptr[i]);  // Print the values
    }

    free(ptr);  // Deallocate the memory
    return 0;
}

malloc 函数为 5 个整数分配内存,free 函数释放内存。始终检查 malloc 是否返回 NULL 以处理分配失败。

为字符串分配内存

本示例演示了如何为字符串分配内存以及使用 free 来释放它。

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

int main() {
    char *str;
    str = (char *)malloc(50 * sizeof(char));  // Allocate memory for a string

    if (str == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    strcpy(str, "Hello there!");  // Copy a string into the allocated memory
    printf("%s\n", str);  // Print the string

    free(str);  // Deallocate the memory
    return 0;
}

malloc 函数为字符串分配内存,free 函数释放它。strcpy 函数用于将字符串复制到已分配的内存中。

重新分配内存

本示例演示了如何使用 realloc 函数重新分配内存。

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

int main() {
    int *ptr;
    ptr = (int *)malloc(5 * sizeof(int));  // Allocate memory for 5 integers

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;  // Assign values to the allocated memory
    }

    ptr = (int *)realloc(ptr, 10 * sizeof(int));  // Reallocate memory for 10 integers

    if (ptr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }

    for (int i = 5; i < 10; i++) {
        ptr[i] = i + 1;  // Assign values to the reallocated memory
    }

    for (int i = 0; i < 10; i++) {
        printf("%d ", ptr[i]);  // Print the values
    }

    free(ptr);  // Deallocate the memory
    return 0;
}

realloc 函数用于调整先前分配的内存块的大小。它可以根据需要扩展或缩小内存块。

为二维数组分配内存

本示例演示了如何使用 malloc 为二维数组分配内存。

2d_array_allocation.c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows = 3, cols = 4;
    int **arr;

    // Allocate memory for rows
    arr = (int **)malloc(rows * sizeof(int *));

    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Allocate memory for columns
    for (int i = 0; i < rows; i++) {
        arr[i] = (int *)malloc(cols * sizeof(int));
        if (arr[i] == NULL) {
            printf("Memory allocation failed\n");
            return 1;
        }
    }

    // Assign values to the 2D array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            arr[i][j] = i * cols + j + 1;
        }
    }

    // Print the 2D array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }

    // Deallocate memory
    for (int i = 0; i < rows; i++) {
        free(arr[i]);
    }
    free(arr);

    return 0;
}

malloc 函数用于为二维数组分配内存。内存是为每一行和每一列单独分配的,并使用 free 来释放内存。

处理内存泄漏

本示例演示了如何通过正确释放内存来避免内存泄漏。

memory_leak.c
#include 
#include 

int main() {
    int *ptr;
    ptr = (int *)malloc(5 * sizeof(int));  // Allocate memory for 5 integers

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;  // Assign values to the allocated memory
    }

    // Memory leak: Forgot to free the allocated memory
    // free(ptr);

    return 0;
}

忘记调用 free 会导致内存泄漏,即分配的内存未被释放。始终确保每次 malloc 调用都有相应的 free 调用。

使用 calloc 进行零初始化内存分配

本示例演示了如何使用 calloc 来分配零初始化的内存。

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

int main() {
    int *ptr;
    ptr = (int *)calloc(5, sizeof(int));  // Allocate and zero-initialize memory for 5 integers

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        printf("%d ", ptr[i]);  // Print the zero-initialized values
    }

    free(ptr);  // Deallocate the memory
    return 0;
}

calloc 函数分配内存并将其初始化为零。当需要零初始化的内存时,它非常有用。

使用 malloc 和 free 的最佳实践

来源

C malloc 文档

在本文中,我们通过实际示例探讨了 C 语言中 mallocfree 的使用,并演示了它们的用法。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面有十多年的经验。

列出所有 C 教程