c程序设计语言_习题8-6_利用malloc()函数,重新实现c语言的库函数calloc()-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

c程序设计语言_习题8-6_利用malloc()函数,重新实现c语言的库函数calloc()

简介:

The standard library function calloc(n,size) returns a pointer to n objects of size size , with the storage initialized to zero. Writecalloc , by calling malloc or by modifying it. 

复制代码
/*
    Exercise 8.6. The standard library function calloc(n, size) returns a pointer to n objects
          of size size, with the storage initialised to zero. Write calloc, by calling 
          malloc or by modifying it.

    Author: Bryan Williams

*/

#include <stdlib.h>
#include <string.h>

/*
  Decided to re-use malloc for this because :
    1) If the implementation of malloc and the memory management layer changes, this will be ok.
    2) Code re-use is great.

*/
void *mycalloc(size_t nmemb, size_t size)
{
  void *Result = NULL;

  /* use malloc to get the memory */
  Result = malloc(nmemb * size);

  /* and clear the memory on successful allocation */
  if(NULL != Result)
  {
    memset(Result, 0x00, nmemb * size);
  }

  /* and return the result */
  return Result;
}

/* simple test driver, by RJH */

#include <stdio.h>

int main(void)
{
  int *p = NULL;
  int i = 0;

  p = mycalloc(100, sizeof *p);
  if(NULL == p)
  {
    printf("mycalloc returned NULL.\n");
  }
  else
  {
    for(i = 0; i < 100; i++)
    {
      printf("%08X ", p[i]);
      if(i % 8 == 7)
      {
    printf("\n");
      }
    }
    printf("\n");
    free(p);
  }

  return 0;
}
复制代码

 本文转自二郎三郎博客园博客,原文链接:http://www.cnblogs.com/haore147/p/3648301.html,如需转载请自行联系原作者


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享: