Skip to content

Commit 3df5a33

Browse files
authored
Implement basic calloc and add unit test for it (#26)
## Description Implement basic calloc and add unit test for it ## Issues <!-- use if this PR fully resolves the issue --> Closes #22 <!-- use if this PR is linked but should not close the issue --> Related: #<issue-number> ## Testing Calloc unit test
1 parent 8f1e9c3 commit 3df5a33

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

src/calloc.cpp

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,22 @@ namespace mem
66

77
void* calloc(size_t num, size_t size)
88
{
9-
(void)num;
10-
(void)size;
11-
return nullptr;
9+
size_t total_size = num * size;
10+
size_t overflow_check = total_size / num;
11+
if (overflow_check != size && num > 0 && size > 0)
12+
{
13+
return nullptr;
14+
}
15+
16+
void* memory_allocation = malloc(total_size);
17+
if (!memory_allocation)
18+
{
19+
return nullptr;
20+
}
21+
22+
memset(memory_allocation, 0, total_size);
23+
24+
return memory_allocation;
1225
}
1326

1427
} // namespace mem

tests/unit/test_calloc.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#include "malloc_from_scratch/memory_allocator.h"
2+
#include "test_utils.h"
3+
4+
int main()
5+
{
6+
size_t amount = 10;
7+
void* ptr = mem::calloc(amount, sizeof(int));
8+
ASSERT_NOT_NULL(ptr);
9+
10+
int* arr = static_cast<int*>(ptr);
11+
for (int i = 0; i < amount; i++)
12+
{
13+
ASSERT_TRUE(arr[i] == 0);
14+
}
15+
16+
TEST_PASS();
17+
}

0 commit comments

Comments
 (0)