Difference between malloc and calloc?

后端 未结 14 1525
感情败类
感情败类 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 04:12

    A difference not yet mentioned: size limit

    void *malloc(size_t size) can only allocate up to SIZE_MAX.

    void *calloc(size_t nmemb, size_t size); can allocate up about SIZE_MAX*SIZE_MAX.

    This ability is not often used in many platforms with linear addressing. Such systems limit calloc() with nmemb * size <= SIZE_MAX.

    Consider a type of 512 bytes called disk_sector and code wants to use lots of sectors. Here, code can only use up to SIZE_MAX/sizeof disk_sector sectors.

    size_t count = SIZE_MAX/sizeof disk_sector;
    disk_sector *p = malloc(count * sizeof *p);
    

    Consider the following which allows an even larger allocation.

    size_t count = something_in_the_range(SIZE_MAX/sizeof disk_sector + 1, SIZE_MAX)
    disk_sector *p = calloc(count, sizeof *p);
    

    Now if such a system can supply such a large allocation is another matter. Most today will not. Yet it has occurred for many years when SIZE_MAX was 65535. Given Moore's law, suspect this will be occurring about 2030 with certain memory models with SIZE_MAX == 4294967295 and memory pools in the 100 of GBytes.

提交回复
热议问题