Question:
Wrote my wrapper over realloc
. Is everything right here? Maybe there are some flaws that I did not notice?
#define qk_realloc(p, n) qk_realloc__(p, &p, n)
/*
=================================
[TEST] The qk_realloc__ function
Функция изменяет размер блока памяти,
на который указывает old. Если операция
выполнена успешно, то old присваивается
адрес нового блока памяти. Если операция
не выполнилась, в куче выделяется НОВЫЙ
блок памяти, в него копируется содержимое
old, старые данные освобождаются и указателю
old присваевает адрес нового блока памяти.
Если память не может быть выделена и для
нового блока, функция возвращает NULL,
при этом входные данные не изменяются.
=================================
*/
void* qk_realloc__(void* old, void* const ptrToOld, const u32 n) {
void* new = realloc(old, n);
if (new != NULL) {
return *((void**) ptrToOld) = new;
}
// Тут должно быть сообщение типа: "не удалось выполнить realloc(n)".
new = qk_malloc(n);
if (new != NULL) {
memmove(new, old, n);
free(old);
return *((void**) ptrToOld) = new;
}
// И тут похожее сообщение...
return NULL;
}
Answer:
The logic of the developer of this shell is completely unclear
-
Why is
old
and a pointer toold
(ptrToOld
) passed to the function at the same time? If you really want to passptrToOld
, then you can also get the value ofold
from it. Why passold
separately? -
Why is the unconditional
memmove(new, old, n);
? What if the new size is larger than the old one? Also, the standardrealloc
allows you to pass a null pointer to it as input. Yourmemmove
does not take this possibility into account. -
Why
ptrToOld
have such a strange type –void* const
? Why is this type not a pointer to a pointer? -
Why did you decide that after
realloc
fails you can domalloc
? Theoretically,realloc
failures can be different, but we understand that almost alwaysrealloc
failure is just a lack of memory. Why do you think that ifrealloc
could not allocate memory, thenmalloc
can? -
*((void**) ptrToOld)
– memory reinterpretation, strict-aliasing violation possible. -
Why
memmove
and notmemcpy
?
And what exactly were you trying to achieve? The first thought was that this wrapper is designed to deal with the shortcomings of the p = realloc(p, ...)
option, but it does not deal with them in any way. So what's the point then?