Skip to content

Commit 588114a

Browse files
authored
Add advanced calloc and realloc features (#41)
## Description Add advanced calloc and realloc features. ## Issues <!-- use if this PR fully resolves the issue --> Closes #33 <!-- use if this PR is linked but should not close the issue --> Related: #<issue-number> ## Testing <!-- Steps or notes on how reviewers can verify. -->
1 parent 916ce84 commit 588114a

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/calloc.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
11
#include "malloc_from_scratch/memory_allocator.h"
2+
23
#include <cstring>
34

45
namespace mem
56
{
67

78
void* calloc(size_t num, size_t size)
89
{
10+
if (num == 0 || size == 0)
11+
{
12+
return nullptr;
13+
}
14+
915
size_t total_size = num * size;
1016
size_t overflow_check = total_size / num;
11-
if (overflow_check != size && num > 0 && size > 0)
17+
if (overflow_check != size)
1218
{
1319
return nullptr;
1420
}

src/realloc.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
#include "malloc_from_scratch/memory_allocator.h"
2+
#include "malloc_from_scratch/memory_internal.h"
3+
4+
#include <cstdlib>
5+
#include <cstring>
26

37
namespace mem
48
{
@@ -16,12 +20,41 @@ void* realloc(void* ptr, size_t new_size)
1620
return nullptr;
1721
}
1822

23+
if (!internal::isPointerInHeap(ptr))
24+
{
25+
return nullptr;
26+
}
27+
28+
internal::MemoryBlock* old_block = internal::getMetadata(ptr);
29+
if (!internal::isValidBlock(old_block))
30+
{
31+
return nullptr;
32+
}
33+
34+
if (!internal::checkCanary(old_block))
35+
{
36+
exit(-1);
37+
}
38+
39+
size_t old_size = old_block->size_;
40+
1941
void* new_ptr = malloc(new_size);
2042
if (new_ptr == nullptr)
2143
{
2244
return nullptr;
2345
}
2446

47+
size_t copy_size;
48+
if (old_size < new_size)
49+
{
50+
copy_size = old_size;
51+
}
52+
else
53+
{
54+
copy_size = new_size;
55+
}
56+
memcpy(new_ptr, ptr, copy_size);
57+
2558
free(ptr);
2659

2760
return new_ptr;

0 commit comments

Comments
 (0)