Skip to content

Commit 72a6145

Browse files
authored
Implement basic realloc and add unit test for it (#27)
## Description Implement basic realloc and add unit test for it ## Issues <!-- use if this PR fully resolves the issue --> Closes #24 <!-- use if this PR is linked but should not close the issue --> Related: #<issue-number> ## Testing Realloc unit test
1 parent 3df5a33 commit 72a6145

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

src/realloc.cpp

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,26 @@ namespace mem
55

66
void* realloc(void* ptr, size_t new_size)
77
{
8-
(void)ptr;
9-
(void)new_size;
10-
return nullptr;
8+
if (ptr == nullptr)
9+
{
10+
return malloc(new_size);
11+
}
12+
13+
if (new_size == 0)
14+
{
15+
free(ptr);
16+
return nullptr;
17+
}
18+
19+
void* new_ptr = malloc(new_size);
20+
if (new_ptr == nullptr)
21+
{
22+
return nullptr;
23+
}
24+
25+
free(ptr);
26+
27+
return new_ptr;
1128
}
1229

1330
} // namespace mem

tests/unit/test_realloc.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#include "malloc_from_scratch/memory_allocator.h"
2+
#include "test_utils.h"
3+
4+
int main()
5+
{
6+
void* null_ptr = mem::realloc(nullptr, 64);
7+
ASSERT_NOT_NULL(null_ptr);
8+
9+
TEST_PASS();
10+
}

0 commit comments

Comments
 (0)