Difference in uses between malloc and calloc

前端 未结 7 469
花落未央
花落未央 2020-12-22 05:00
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions

7条回答
  •  太阳男子
    2020-12-22 05:30

    Look at an implementation of calloc to see the differences. It's probably something like this:

    // SIZE_MAX is defined in stdint.h from C99
    void *calloc( size_t N, size_t S)
    {
        void *ret;
        size_t NBYTES;
    
        // check for overflow of size_t type
        if (N > SIZE_MAX / S) return NULL;
    
        NBYTES = N * S;
        ret = malloc( NBYTES);
        if (ret != NULL)
        {
            memset( ret, 0, NBYTES);
        }
    
        return ret;
    }
    

提交回复
热议问题