malloc 与 free
malloc 和 free 是 C 语言动态内存管理的基础函数。malloc 在堆上分配指定字节数的内存,返回指向该内存的指针;free 释放 malloc 分配的内存,将其归还给系统。正确使用这对函数是避免内存泄漏和悬垂指针的关键。
malloc 基本用法
#include <stdlib.h>
/* 分配能容纳 10 个 int 的内存 */
int *arr = malloc(10 * sizeof(int));
if (arr == NULL) {
/* 分配失败处理 */
perror("malloc failed");
exit(1);
}
/* 使用内存 */
for (int i = 0; i < 10; i++)
arr[i] = i;
/* 释放 */
free(arr);
arr = NULL; /* 避免悬垂指针 */
分配结构体
struct Node {
int data;
struct Node *next;
};
struct Node *node = malloc(sizeof(struct Node));
if (node != NULL) {
node->data = 10;
node->next = NULL;
/* 使用 */
free(node);
}
分配数组
/* 分配二维数组(连续内存) */
int rows = 3, cols = 4;
int *matrix = malloc(rows * cols * sizeof(int));
/* 访问:matrix[i * cols + j] */
matrix[1 * cols + 2] = 10;
free(matrix);
常见错误
分配失败未检查:
int *p = malloc(100);
p[0] = 10; /* 危险:如果 p 为 NULL,崩溃 */
/* 正确 */
int *p = malloc(100);
if (p != NULL)
p[0] = 10;
重复释放:
int *p = malloc(100);
free(p);
free(p); /* 未定义行为:双重释放 */
释放后使用:
int *p = malloc(100);
free(p);
p[0] = 10; /* 未定义行为:使用已释放内存 */
释放非 malloc 内存:
int arr[10];
free(arr); /* 未定义行为:arr 不是 malloc 分配的 */
最佳实践
- 始终检查
malloc返回值 - 配对使用
malloc/free - 释放后将指针置
NULL - 用
sizeof计算大小,不要硬编码 - 分配大小为 0 时行为未定义,避免