Can realloc fail (return NULL) when trimming?

后端 未结 7 711
误落风尘
误落风尘 2020-12-19 00:15

If do the next:

int* array = malloc(10 * sizeof(int));

and them I use realloc:

array = realloc(array, 5 * sizeof(int));
         


        
7条回答
  •  误落风尘
    2020-12-19 00:56

    realloc will not fails in shrinking the existing memory, so it will not return NULL. It can return NULL only if fails during expansion.

    But shrinking can fail in some architecture, where realloc can be implemented in a different manner like allocating a smaller size memory separately and freeing the old memory to avoid fragmentation. In that case shrinking memory can return NULL. But its very rare implementation.

    But its better to be in a safer side, to keep NULL checks after shrinking the memory also.

提交回复
热议问题