38 lines
1.1 KiB
C
38 lines
1.1 KiB
C
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/ksys.h>
|
|
#include "_mem.h"
|
|
|
|
void* realloc(void* ptr, size_t newsize)
|
|
{
|
|
// Handle NULL pointer.
|
|
if (ptr == NULL)
|
|
return NULL;
|
|
|
|
// Get a pointer to the mem_node header from the user data pointer.
|
|
struct mem_node* node = GET_MEM_NODE_HEADER(ptr);
|
|
void* new_ptr;
|
|
|
|
// If the new size is smaller than or equal to the current size:
|
|
if (node->size >= newsize) {
|
|
// Update the free space in the current node.
|
|
node->free = node->size - newsize;
|
|
// Return the original pointer.
|
|
new_ptr = ptr;
|
|
} else {
|
|
// Allocate a new block of memory with the new size.
|
|
new_ptr = malloc(newsize);
|
|
|
|
// If both the old pointer and the new pointer are not NULL:
|
|
if (ptr != NULL && new_ptr != NULL) {
|
|
// Copy the data from the old block to the new block.
|
|
memcpy(new_ptr, ptr, min(newsize, node->size));
|
|
// Free the old block.
|
|
free(ptr);
|
|
}
|
|
}
|
|
|
|
// Return the new pointer.
|
|
return new_ptr;
|
|
}
|