What is the correct usage of realloc() when it fails and returns NULL?

后端 未结 4 1856
Happy的楠姐
Happy的楠姐 2020-12-31 04:39

Can anyone summarize what is the correct usage of realloc()?

What do you do when realloc() fails?

From what I have seen so far, it

相关标签:
4条回答
  • 2020-12-31 05:15

    From http://www.c-faq.com/malloc/realloc.html

    If realloc cannot find enough space at all, it returns a null pointer, and leaves the previous region allocated.

    Therefore you would indeed need to free the previously allocated memory still.

    0 讨论(0)
  • 2020-12-31 05:20

    It depends on what you want to do. When realloc fails, what is it you want to do: free the old block or keep it alive and unchanged? If you want to free it, then free it.

    Keep in mind also, that in C89/90 if you make a realloc request with zero target size, realloc function may return a null pointer even though the original memory was successfully deallocated. This was a defect in C89/90, since there was no way to tell the success from failure on null return.

    In C99 this defect was fixed and the strict relationship between null return and success/failure of reallocation was guaranteed. In C99 null return always means total failure of realloc.

    0 讨论(0)
  • 2020-12-31 05:23

    If realloc fails I don't think you would want to delete the original block since you will lose it. It seems like realloc will resize the old block (or return a pointer to a new location) and on success will return a pointer to the old block (or new location) and on failure will return NULL. If it couldn't allocate a new block the old block is untouched.

    0 讨论(0)
  • 2020-12-31 05:23

    Edit: Correction, some people are bashing me for what I said, the way you allocated your pointer seems to be best practice among them, I was taught to always go with type casts in the sizeof(), but apparently your way is more correct, so disregard what I said =)

    Taking a peek at http://en.wikipedia.org/wiki/Malloc#realloc before might have done you some good.

    You don't quite understand sizeof() - it has the value of the size of the argument you pass to it in bytes. For example, sizeof(int) will be 4 on most 32 bit systems but you should still use sizeof(int) instead of 4 because compiling your code on a 64 bit system (just as an example) will make that value equal to 8 and your code will still compile fine. What are you allocating memory for? Pointers? If so you should use sizeof(void*) instead (you can say sizeof(int*) but it's common convention not to mention to the compiler what you want to store at those pointers, since all pointers should be the same size - so most programmers say sizeof(void*)), if you need space for characters use sizeof(char) and so on.

    You are however right to store the return value of realloc() in a new pointer and check it, though a lot of programmers will assume the system always has enough memory and get away with it.

    0 讨论(0)
提交回复
热议问题