Difference between malloc and calloc?

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

    Difference 1:

    malloc() usually allocates the memory block and it is initialized memory segment.

    calloc() allocates the memory block and initialize all the memory block to 0.

    Difference 2:

    If you consider malloc() syntax, it will take only 1 argument. Consider the following example below:

    data_type ptr = (cast_type *)malloc( sizeof(data_type)*no_of_blocks );
    

    Ex: If you want to allocate 10 block of memory for int type,

    int *ptr = (int *) malloc(sizeof(int) * 10 );
    

    If you consider calloc() syntax, it will take 2 arguments. Consider the following example below:

    data_type ptr = (cast_type *)calloc(no_of_blocks, (sizeof(data_type)));
    

    Ex: if you want to allocate 10 blocks of memory for int type and Initialize all that to ZERO,

    int *ptr = (int *) calloc(10, (sizeof(int)));
    

    Similarity:

    Both malloc() and calloc() will return void* by default if they are not type casted .!

提交回复
热议问题