Wrapper over realloc


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);
        return *((void**) ptrToOld) = new;

    // И тут похожее сообщение...

    return NULL;


The logic of the developer of this shell is completely unclear

  1. Why is old and a pointer to old ( ptrToOld ) passed to the function at the same time? If you really want to pass ptrToOld , then you can also get the value of old from it. Why pass old separately?

  2. Why is the unconditional memmove(new, old, n); ? What if the new size is larger than the old one? Also, the standard realloc allows you to pass a null pointer to it as input. Your memmove does not take this possibility into account.

  3. Why ptrToOld have such a strange type – void* const ? Why is this type not a pointer to a pointer?

  4. Why did you decide that after realloc fails you can do malloc ? Theoretically, realloc failures can be different, but we understand that almost always realloc failure is just a lack of memory. Why do you think that if realloc could not allocate memory, then malloc can?

  5. *((void**) ptrToOld) – memory reinterpretation, strict-aliasing violation possible.

  6. Why memmove and not memcpy ?

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?

Scroll to Top