> For the complete documentation index, see [llms.txt](https://valineliu.gitbook.io/deuterium-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://valineliu.gitbook.io/deuterium-wiki/reading/cs-jing-dian-shu-ji/csapp-3e-homework-solution/2.-representing-and-manipulating-information/2.76-calloc.md).

# 2.76 calloc

★

**Problem**:

The library function `calloc` has the following declaration:

```c
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:

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

Code:

```c
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;
}
```

###
