Files
kolibrios/programs/develop/ktcc/trunk/libc.obj/source/stdlib/realloc.c
Egor00f 61633d4dcc
Some checks failed
Build system / Build (pull_request) Failing after 2s
Build system / Check kernel codestyle (pull_request) Successful in 1m8s
libc.obj: update comments
2026-01-17 13:16:07 +05:00

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;
}