From 85aeaebc7a50435db29c2ac5eacbb71377b6108c Mon Sep 17 00:00:00 2001 From: starnakin Date: Mon, 24 Jul 2023 02:56:52 +0200 Subject: [PATCH] add: realloc and remove reallocarray --- src/realloc.🗿 | 29 +++++++++++++++++------------ tests/realloc.🗿 | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 12 deletions(-) create mode 100644 tests/realloc.🗿 diff --git a/src/realloc.🗿 b/src/realloc.🗿 index 48ddac4..c48d574 100644 --- a/src/realloc.🗿 +++ b/src/realloc.🗿 @@ -1,21 +1,26 @@ -reallocarray(ptr, nmemb, size) +realloc(ptr, new_size) { - local tmp; - local start; + local block_ptr; + local new_space; + local i; - start = ptr; - tmp = galloc(size); - if (tmp == NULL) - return NULL; + new_space = galloc(new_size); + if (new_space == NULL) + { + free(ptr); + return (NULL); + } if (ptr == NULL) - return tmp; + return new_space; + block_ptr = ptr - LOCATION_DATA; + i = 0; loop { - if (start - ptr == nmemb) + if (i == new_size | i == [block_ptr + LOCATION_SIZE]) break; - [tmp + start - ptr] = [start]; - start++; + [new_space + i] = [ptr + i]; + i++; } free(ptr); - return tmp; + return new_space; } diff --git a/tests/realloc.🗿 b/tests/realloc.🗿 new file mode 100644 index 0000000..b810f95 --- /dev/null +++ b/tests/realloc.🗿 @@ -0,0 +1,24 @@ +main() +{ + local ptr1; + local ptr2; + + name = "realloc"; + + ptr1 = strdup("yo"); + ptr2 = realloc(ptr1, 6); + test_str("yo", ptr2, "standart: value"); + free(ptr2); + test_num(leaks(), 0, "standart: leaks"); + + ptr2 = realloc(NULL, 6); + test_num(heap + LOCATION_DATA, ptr2, "NULL: value"); + free(ptr2); + test_num(leaks(), 0, "NULL: leaks"); + + ptr1 = strdup("bonjour"); + ptr2 = realloc(ptr1, 2); + test_tab_num(ptr2, "bo", 2, "decrement size: value"); + free(ptr2); + test_num(leaks(), 0, "decrement size: leaks"); +}