2.76 calloc

Problem:

The library function calloc has the following declaration:

void *calloc(size_t nmemb, size_t size);

According to the library documentation, "The calloc function allocates memory for an array of nmemb elements of size bytes each. The memory is set to zero. If nmemeb or size is zero, then calloc return NULL".

Write an implementation of calloc that performs the allocation by a call to malloc and sets the memory to zero via memset. Your code should not have any vulnerabilities due to arithmetic overflow, and it should work correctly regardless of the number of bits used to represent data of type size_t.

As a reference, functions malloc and memset have the following declarations:

void *malloc(size_t size);
void *memset(void *s, int c, size_t n);

Code:

void *my_calloc(size_t nmemb, size_t size) {
    if (nmemb == 0 || size == 0) {
        return null;
    }
    size_t buff_size = nmemb * size;
    if (buff_size/nmemb == size) {
        void *pbuf = malloc(buff_size);
        if (pbuf != null) {
            memset(pbuf, 0, buff_size);
        }
        return pbuf;
    }
    return null;
}

Last updated