Chinaunix首页 | 论坛 | 博客
  • 博客访问: 66723
  • 博文数量: 17
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 154
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-12 22:56
个人简介

不卑不亢

文章分类

全部博文(17)

文章存档

2016年(1)

2015年(13)

2014年(3)

分类: C/C++

2015-03-21 14:16:06


点击(此处)折叠或打开

  1. /*定义一个不易发生错误的内存分配器*/
  2. #include <stdlib.h>

  3. #define MALLOC(num, type) (type *)alloc(num * sizeof(type))
  4. extern void *alloc(size_t size);

  5. /*一个不易发生错误的内存分配器的实现*/
  6. #include <stdio.h>
  7. #include "alloc.h"

  8. void *alloc(size_t size)
  9. {
  10.     void *new_num;

  11.     new_num = malloc(size);

  12.     /*请求所需的内存,并检查是否分配成功*/
  13.     if (NULL == new_num) {
  14.         printf("Out of Memory!\n");
  15.         exit(1);
  16.     }

  17.     return new_num;
  18. }

  19. #include "alloc.h"

  20. int function()
  21. {
  22.     int *new_memory;

  23.     new_memory = MALLOC(25, int);

  24.     return 0;
  25. }

  26. int main()
  27. {
  28.     function();

  29.     return 0;
  30. }

阅读(1191) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~