Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

void *calloc(size_t nmemb, size_t size); According to the library documentation,

ID: 3664962 • Letter: V

Question

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 each. The memory is set to zero. If nmemb or size is zero, then calloc returns NULL.” Write an implementation of calloc that performs the allocation by a call to malloc and sets the memory to zero using 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); Note: I do not want to use the #include

Explanation / Answer

below is the implementation of calloc that performs the allocation by a call to malloc and then sets the memory to zero using memset void *calloc(size_t nmemb, size_t size) { size_t total = nmemb * size; void *p = malloc(total); if (!p) return NULL; return memset(p, 0, total); }