Difference between malloc and calloc?

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

    Number of blocks:
    malloc() assigns single block of requested memory,
    calloc() assigns multiple blocks of the requested memory

    Initialization:
    malloc() - doesn't clear and initialize the allocated memory.
    calloc() - initializes the allocated memory by zero.

    Speed:
    malloc() is fast.
    calloc() is slower than malloc().

    Arguments & Syntax:
    malloc() takes 1 argument:

    1. bytes

      • The number of bytes to be allocated

    calloc() takes 2 arguments:

    1. length

      • the number of blocks of memory to be allocated
    2. bytes

      • the number of bytes to be allocated at each block of memory
    void *malloc(size_t bytes);         
    void *calloc(size_t length, size_t bytes);      
    

    Manner of memory Allocation:
    The malloc function assigns memory of the desired 'size' from the available heap.
    The calloc function assigns memory that is the size of what’s equal to ‘num *size’.

    Meaning on name:
    The name malloc means "memory allocation".
    The name calloc means "contiguous allocation".

提交回复
热议问题