Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions src/calloc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 17 additions & 0 deletions tests/unit/test_calloc.cpp
Original file line number Diff line number Diff line change
@@ -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<int*>(ptr);
for (int i = 0; i < amount; i++)
{
ASSERT_TRUE(arr[i] == 0);
}

TEST_PASS();
}