make our own realloc function
| 23 | |
| 24 | // make our own realloc function |
| 25 | void* realloc(void* ptr, size_t new_size) { |
| 26 | if (ptr == NULL) { |
| 27 | return malloc(new_size); |
| 28 | } |
| 29 | |
| 30 | // You need to keep track of the old size to properly copy the data |
| 31 | int old_size = ptrsize(ptr); |
| 32 | |
| 33 | void* new_ptr = malloc(new_size); |
| 34 | if (new_ptr == NULL) { |
| 35 | return NULL; // Allocation failed |
| 36 | } |
| 37 | |
| 38 | // Copy the old data to the new location |
| 39 | memcpy(new_ptr, ptr, old_size < new_size ? old_size : new_size); |
| 40 | |
| 41 | // Free the old location |
| 42 | free(ptr); |
| 43 | |
| 44 | return new_ptr; |
| 45 | } |
| 46 | |
| 47 | // A simple implementation of atoi |
| 48 | int atoi(const char* str) { |