diff --git a/src/calloc.cpp b/src/calloc.cpp index b3c0bef..ccf931c 100644 --- a/src/calloc.cpp +++ b/src/calloc.cpp @@ -6,9 +6,22 @@ namespace mem void* calloc(size_t num, size_t size) { - (void)num; - (void)size; - return nullptr; + size_t total_size = num * size; + size_t overflow_check = total_size / num; + if (overflow_check != size && num > 0 && size > 0) + { + return nullptr; + } + + void* memory_allocation = malloc(total_size); + if (!memory_allocation) + { + return nullptr; + } + + memset(memory_allocation, 0, total_size); + + return memory_allocation; } } // namespace mem diff --git a/tests/unit/test_calloc.cpp b/tests/unit/test_calloc.cpp new file mode 100644 index 0000000..2657ced --- /dev/null +++ b/tests/unit/test_calloc.cpp @@ -0,0 +1,17 @@ +#include "malloc_from_scratch/memory_allocator.h" +#include "test_utils.h" + +int main() +{ + size_t amount = 10; + void* ptr = mem::calloc(amount, sizeof(int)); + ASSERT_NOT_NULL(ptr); + + int* arr = static_cast(ptr); + for (int i = 0; i < amount; i++) + { + ASSERT_TRUE(arr[i] == 0); + } + + TEST_PASS(); +}