Difference between malloc and calloc?

后端 未结 14 1505
感情败类
感情败类 2020-11-22 03:40

What is the difference between doing:

ptr = (char **) malloc (MAXELEMS * sizeof(char *));

or:

ptr = (char **) calloc (MAXEL         


        
14条回答
  •  长情又很酷
    2020-11-22 03:56

    calloc is generally malloc+memset to 0

    It is generally slightly better to use malloc+memset explicitly, especially when you are doing something like:

    ptr=malloc(sizeof(Item));
    memset(ptr, 0, sizeof(Item));
    

    That is better because sizeof(Item) is know to the compiler at compile time and the compiler will in most cases replace it with the best possible instructions to zero memory. On the other hand if memset is happening in calloc, the parameter size of the allocation is not compiled in in the calloc code and real memset is often called, which would typically contain code to do byte-by-byte fill up until long boundary, than cycle to fill up memory in sizeof(long) chunks and finally byte-by-byte fill up of the remaining space. Even if the allocator is smart enough to call some aligned_memset it will still be a generic loop.

    One notable exception would be when you are doing malloc/calloc of a very large chunk of memory (some power_of_two kilobytes) in which case allocation may be done directly from kernel. As OS kernels will typically zero out all memory they give away for security reasons, smart enough calloc might just return it withoud additional zeroing. Again - if you are just allocating something you know is small, you may be better off with malloc+memset performance-wise.

提交回复
热议问题