注意事项
- 检查返回值:
malloc
函数在分配内存成功时返回指向所分配内存起始地址的指针,若分配失败则返回NULL
。每次调用malloc
后都应检查返回值,避免使用空指针导致程序崩溃。
- 分配内存大小:传递给
malloc
的参数应为所需分配内存的字节数。需要确保计算的字节数准确,尤其是在处理复杂数据结构(如结构体数组)时。
- 内存对齐:
malloc
分配的内存通常满足系统默认的内存对齐要求,但在特定情况下(如处理特定硬件或遵循特殊协议),可能需要手动处理内存对齐。
- 释放内存:使用完动态分配的内存后,必须调用
free
函数释放,以避免内存泄漏。注意只能释放由malloc
、calloc
或realloc
分配的内存,且不能重复释放同一块内存。
- 内存碎片:频繁地分配和释放小内存块可能会导致内存碎片,降低内存使用效率。可以考虑使用内存池等技术来减少碎片。
可能出现的错误及避免方法
- 空指针引用
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
*ptr = 10; // 未检查malloc返回值,可能是NULL
printf("%d\n", *ptr);
return 0;
}
- **避免方法**:检查`malloc`返回值
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
perror("malloc");
return 1;
}
*ptr = 10;
printf("%d\n", *ptr);
free(ptr);
return 0;
}
- 内存泄漏
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
perror("malloc");
return 1;
}
// 这里忘记释放内存
return 0;
}
- **避免方法**:在合适的位置调用`free`函数释放内存
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
perror("malloc");
return 1;
}
*ptr = 10;
printf("%d\n", *ptr);
free(ptr);
return 0;
}
- 重复释放内存
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
perror("malloc");
return 1;
}
free(ptr);
free(ptr); // 重复释放
return 0;
}
- **避免方法**:确保只对同一块内存调用一次`free`,释放后将指针置为`NULL`,防止误操作
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
perror("malloc");
return 1;
}
free(ptr);
ptr = NULL;
return 0;
}