alloc.h
/*
**定义一个不易发生错误的内存分配器
*/
#include<stdlib.h>
#define 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;
}
test.c
#include<stdio.h>
//#include<malloc.h>
#include "alloc.h"
//#undef malloc
void main()
{
void *p;
p = (void*)MALLOC(3, int);
printf("sizof(p) = %d/n", p);
}