Can realloc fail (return NULL) when trimming?

后端 未结 7 710
误落风尘
误落风尘 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 01:03

    The other answers have already nailed the question, but assuming you know the realloc call is a "trimming", you can wrap it with:

    void *safe_trim(void *p, size_t n) {
        void *p2 = realloc(p, n);
        return p2 ? p2 : p;
    }
    

    and the return value will always point to an object of size n.

    In any case, since the implementation of realloc knows the size of the object and can therefore determine that it's "trimming", it would be pathologically bad from a quality-of-implementation standpoint not to perform the above logic internally. But since realloc is not required to do this, you should do it yourself, either with the above wrapper or with analogous inline logic when you call realloc.

提交回复
热议问题