add: realloc and remove reallocarray

This commit is contained in:
starnakin 2023-07-24 02:56:52 +02:00
parent 3443ed76e8
commit 85aeaebc7a
2 changed files with 41 additions and 12 deletions

View File

@ -1,21 +1,26 @@
reallocarray(ptr, nmemb, size) realloc(ptr, new_size)
{ {
local tmp; local block_ptr;
local start; local new_space;
local i;
start = ptr; new_space = galloc(new_size);
tmp = galloc(size); if (new_space == NULL)
if (tmp == NULL) {
return NULL; free(ptr);
return (NULL);
}
if (ptr == NULL) if (ptr == NULL)
return tmp; return new_space;
block_ptr = ptr - LOCATION_DATA;
i = 0;
loop loop
{ {
if (start - ptr == nmemb) if (i == new_size | i == [block_ptr + LOCATION_SIZE])
break; break;
[tmp + start - ptr] = [start]; [new_space + i] = [ptr + i];
start++; i++;
} }
free(ptr); free(ptr);
return tmp; return new_space;
} }

24
tests/realloc.🗿 Normal file
View File

@ -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");
}