Skip to content

Commit a21dd6e

Browse files
Improved realloc.
1 parent 69b429d commit a21dd6e

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

source/kernel/C/heap.c

+14-12
Original file line numberDiff line numberDiff line change
@@ -97,17 +97,14 @@ void free(void* ptr) {
9797

9898
void* realloc(void* ptr, size_t size) {
9999
if (ptr == NULL) {
100-
return malloc(size);
100+
return malloc(size); // Use your malloc
101101
}
102102

103103
if (size == 0) {
104-
free(ptr);
104+
free(ptr); // Use your free
105105
return NULL;
106106
}
107107

108-
// Align allocation to page size
109-
size_t aligned_size = (size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
110-
111108
Node* current = head;
112109
while (current != NULL && current->data != ptr) {
113110
current = current->next;
@@ -117,19 +114,24 @@ void* realloc(void* ptr, size_t size) {
117114
return NULL; // Invalid pointer
118115
}
119116

120-
if (current->size >= aligned_size) {
121-
// Existing block is large enough
122-
return ptr;
117+
if (current->size == size) {
118+
return ptr; // No change needed
123119
}
124120

125-
// Allocate a new block and copy data
126-
void* new_ptr = malloc(size);
121+
// Try to expand in place (more efficient)
122+
// ... (Implementation for expanding in place, if possible) ...
123+
124+
// If expanding in place isn't possible, allocate a new block
125+
void* new_ptr = malloc(size); // Use your malloc
127126
if (new_ptr == NULL) {
128127
return NULL;
129128
}
130129

131-
memcpy(new_ptr, ptr, current->size);
132-
free(ptr);
130+
size_t copy_size = (size < current->size) ? size : current->size; // Don't copy more than the smaller size
131+
memcpy(new_ptr, ptr, copy_size);
132+
free(ptr); // Use your free
133133

134+
current->data = new_ptr;
135+
current->size = size; // Update the size!
134136
return new_ptr;
135137
}

0 commit comments

Comments
 (0)