Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359787
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-04-21 16:36:28

  • what 's difference between calloc and malloc ?

calloc(m, n) is essentially equivalent to

p = malloc(m * n);
+
memset(p, 0, m * n);


There is no important difference between the two other than the number of arguments and the zero fill.

Malloc:
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
Calloc:
Allocate space for array in memory
Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
The effective result is the allocation of an zero-initialized memory block of (num * size) bytes.
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. int
  4. main(void)
  5. {
  6.         int *pa = (int *)malloc(sizeof(int)*5);
  7.         int *pb = (int *)calloc(sizeof(int), 5);
  8.         if (pa == NULL || pb == NULL) {
  9.                 printf("out of memory\n");
  10.                 return (-1);
  11.         }
  12.         int i;
  13.         for (i = 0; i < 5; i++)
  14.                 printf("%d,", *(pa+i)); // sometimes error
  15.         printf("\n");

  16.         for (i = 0; i < 5; i++)
  17.                 printf("%d,", *(pb+i));
  18.         printf("\n");

  19.         free(pa);
  20.         free(pb);
  21.         return (0);
  22. }

阅读(875) | 评论(1) | 转发(0) |
0

上一篇:拷贝构造函数

下一篇:enum & union

给主人留下些什么吧!~~

onezeroone2011-04-24 16:25:09

calloc---nitializes all its bits to zero.