Difference between malloc and calloc?

后端 未结 14 1890
感情败类
感情败类 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:09

    One often-overlooked advantage of calloc is that (conformant implementations of) it will help protect you against integer overflow vulnerabilities. Compare:

    size_t count = get_int32(file);
    struct foo *bar = malloc(count * sizeof *bar);
    

    vs.

    size_t count = get_int32(file);
    struct foo *bar = calloc(count, sizeof *bar);
    

    The former could result in a tiny allocation and subsequent buffer overflows, if count is greater than SIZE_MAX/sizeof *bar. The latter will automatically fail in this case since an object that large cannot be created.

    Of course you may have to be on the lookout for non-conformant implementations which simply ignore the possibility of overflow... If this is a concern on platforms you target, you'll have to do a manual test for overflow anyway.

提交回复
热议问题