Difference between malloc and calloc?

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

    There are two differences.
    First, is in the number of arguments. malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments.
    Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.

    • calloc() allocates a memory area, the length will be the product of its parameters. calloc fills the memory with ZERO's and returns a pointer to first byte. If it fails to locate enough space it returns a NULL pointer.

    Syntax: ptr_var=(cast_type *)calloc(no_of_blocks , size_of_each_block); i.e. ptr_var=(type *)calloc(n,s);

    • malloc() allocates a single block of memory of REQUSTED SIZE and returns a pointer to first byte. If it fails to locate requsted amount of memory it returns a null pointer.

    Syntax: ptr_var=(cast_type *)malloc(Size_in_bytes); The malloc() function take one argument, which is the number of bytes to allocate, while the calloc() function takes two arguments, one being the number of elements, and the other being the number of bytes to allocate for each of those elements. Also, calloc() initializes the allocated space to zeroes, while malloc() does not.

    0 讨论(0)
  • 2020-11-22 04:19

    Both malloc and calloc allocate memory, but calloc initialises all the bits to zero whereas malloc doesn't.

    Calloc could be said to be equivalent to malloc + memset with 0 (where memset sets the specified bits of memory to zero).

    So if initialization to zero is not necessary, then using malloc could be faster.

    0 讨论(0)
提交回复
热议问题