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
8 changes: 7 additions & 1 deletion src/calloc.cpp
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
#include "malloc_from_scratch/memory_allocator.h"

#include <cstring>

namespace mem
{

void* calloc(size_t num, size_t size)
{
if (num == 0 || size == 0)
{
return nullptr;
}

size_t total_size = num * size;
size_t overflow_check = total_size / num;
if (overflow_check != size && num > 0 && size > 0)
if (overflow_check != size)
{
return nullptr;
}
Expand Down
33 changes: 33 additions & 0 deletions src/realloc.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
#include "malloc_from_scratch/memory_allocator.h"
#include "malloc_from_scratch/memory_internal.h"

#include <cstdlib>
#include <cstring>

namespace mem
{
Expand All @@ -16,12 +20,41 @@ void* realloc(void* ptr, size_t new_size)
return nullptr;
}

if (!internal::isPointerInHeap(ptr))
{
return nullptr;
}

internal::MemoryBlock* old_block = internal::getMetadata(ptr);
if (!internal::isValidBlock(old_block))
{
return nullptr;
}

if (!internal::checkCanary(old_block))
{
exit(-1);
}

size_t old_size = old_block->size_;

void* new_ptr = malloc(new_size);
if (new_ptr == nullptr)
{
return nullptr;
}

size_t copy_size;
if (old_size < new_size)
{
copy_size = old_size;
}
else
{
copy_size = new_size;
}
memcpy(new_ptr, ptr, copy_size);

free(ptr);

return new_ptr;
Expand Down