动态内存分配最常见的错误就是忘记检查所请求的内存是否分配成功. 可以利用 宏 实现安全的动态内存分配.
// alloc.h
#include <stdlib.h>
#define malloc 不要直接使用malloc // 直接使用malloc将无法编译
#define MALLOC(num, type) (type *)alloc((num) * sizeof(type))
extern void *alloc(size_t size);
// alloc.c
#include <stdio.h>
#include "alloc.h"
#undef malloc
void *alloc(size_t size)
{
void *new_mem;
new_mem = malloc(size);
if (new_mem == NULL) {
printf("Out of memory!\n");
exit(1);
}
return new_mem;
}
// main.c
#include <stdio.h>
#include "alloc.h"
int main()
{
int *new_mem;
new_mem = MALLOC(25, int);
// ...
free(new_mem);
return 0;
}