简体   繁体   English

memory 分配是如何由 malloc 和 calloc function 在 Z0D61F8370CAD14D412F70B8D 中完成的?

[英]How is the memory allocation done by malloc and calloc function in C?

malloc() allocates a single block of memory whereas calloc() allocates multiple blocks of memory, each block with the same size. malloc() 分配 memory 的单个块,而 calloc() 分配 memory 的多个块,每个块具有相同的大小。

How do they differ from each other in internal implementation?它们在内部实现方面有何不同?

I tried the below code and tried to figure out the difference between the internal implementation of malloc and calloc (considering the above-quoted text).我尝试了下面的代码并试图找出 malloc 和 calloc 的内部实现之间的区别(考虑到上面引用的文本)。

#include<stdio.h>
#include<stdlib.h>
int main()
{
   int *p=(int*)malloc(2*sizeof(int));
   p[0]=3;
   p[1]=4;
   printf("%d\t%d",p[0],p[1]);
   free(p);
   int *q=(int*)calloc(2,sizeof(int));
   q[0]=1;
   q[1]=2;
   printf("\n%d\t%d",q[0],q[1]);
   free(q);
   return 0;
}

But I didn't find any difference(from the output) between these two functions.但是我没有发现这两个函数之间有任何区别(从输出中)。 What change should I do to understand the internal implementation of both functions?我应该做些什么改变来理解这两个功能的内部实现? Here my meaning to the internal implementation is mentioned in the above-quoted text.在上面引用的文本中提到了我对内部实现的含义。

I hope you got my question.我希望你能得到我的问题。

Thanks谢谢

There is no big difference with the internal implementation perspective of both, or on most implementations calloc does use malloc followed by memset to zero the memory allocated as shown below example snippet.两者的内部实现角度没有太大区别,或者在大多数实现中calloc确实使用malloc后跟memset将 memory 分配为零,如下面的示例片段所示。 Refer to calloc implementation.参考calloc实现。

void *calloc(size_t n, size_t elem_size)
{
    const size_t nbytes = n * elem_size;
    void *p = malloc(nbytes);
    if (p != NULL) {
       memset(p, 0, nbytes);
    }
    return p;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM