Implement calloc() (accidentally got dropped with the malloc rewrite).
This commit is contained in:
parent
36ab90385f
commit
9481487e3d
23
lang/cem/libcc.ansi/malloc/calloc.c
Normal file
23
lang/cem/libcc.ansi/malloc/calloc.c
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
void* calloc(size_t nmemb, size_t size)
|
||||||
|
{
|
||||||
|
size_t bytes = nmemb * size;
|
||||||
|
void* ptr;
|
||||||
|
|
||||||
|
/* Test for overflow.
|
||||||
|
* See http://stackoverflow.com/questions/1815367/multiplication-of-large-numbers-how-to-catch-overflow
|
||||||
|
*/
|
||||||
|
|
||||||
|
if ((nmemb == 0) || (size == 0) || (nmemb > (SIZE_MAX / size)))
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
ptr = malloc(bytes);
|
||||||
|
if (!ptr)
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
memset(ptr, 0, bytes);
|
||||||
|
return ptr;
|
||||||
|
}
|
Loading…
Reference in a new issue