开发者

C - If realloc is used is free necessary?

开发者 https://www.devze.com 2023-02-19 20:16 出处:网络
When using realloc is the memory automatically freed?Or is it necessary to use free with realloc?Which of the following is correct?

When using realloc is the memory automatically freed? Or is it necessary to use free with realloc? Which of the following is correct?

//Situation A
ptr1 = realloc(ptr1, 3 * sizeof(int));

//Situation B
ptr1 = rea开发者_如何学运维lloc(ptr2, 3 * sizeof(int));
free(ptr1);
ptr1 = ptr2;


Neither is correct. realloc() can return a pointer to newly allocated memory or NULL on error. What you should do is check the return value:

ptr1 = realloc(ptr2, 3 * sizeof(int));
if (!ptr1) {
    /* Do something here to handle the failure */
    /* ptr2 is still pointing to allocated memory, so you may need to free(ptr2) here */
}

/* Success! ptr1 is now pointing to allocated memory and ptr2 was deallocated already */
free(ptr1);


After ptr1 = realloc(ptr2, 3 * sizeof(int)); ptr2 is invalid and should not be used. You need to free ptr1 only. In some cases the return value of realloc will be the same value you passed in though.

You can safely consider ptr1=realloc(ptr2, ... as equivalent to this:

ptr1 = malloc(...);
memcpy(ptr1, ptr2, ...);
free(ptr2);

This is what happens in most cases, unless the new size still fits in the old memory block - then realloc could return the original memory block.

As other allocation functions, realloc returns NULL if it fails - you may want to check for that.


realloc() automatically frees the original memory, or returns it unchanged (aside from metadata) if you realloc() to a smaller size or there is unallocated memory available to simply expand the original allocation in place.


According to http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/, realloc returns the new memory block if the reallocation is successful, keeps the original memory block if not. Standard usage would look like this:

ptr2 = realloc(ptr1, new_size);
if (ptr2 == NULL) {
   //ptr1 still contains pointer to original array
} else {
   //ptr2 contains new array, ptr1 is invalid
}


In both situations, ptr1 must be freed.

Situation B is more complex because ptr2 potentially points to freed space. Or not. It depends on whether it could be reallocated. ptr2 should not be used after the realloc in B.

0

精彩评论

暂无评论...
验证码 换一张
取 消