Using realloc to shrink the allocated memory

荒凉一梦 提交于 2019-11-27 05:16:58

问题


Simple question about the realloc function in C: If I use realloc to shrink the memory block that a pointer is pointing to, does the "extra" memory get freed? Or does it need to be freed manually somehow?

For example, if I do

int *myPointer = malloc(100*sizeof(int));
myPointer = realloc(myPointer,50*sizeof(int));
free(myPointer);

Will I have a memory leak?


回答1:


No, you won't have a memory leak. realloc will simply mark the rest "available" for future malloc operations.

But you still have to free myPointer later on. As an aside, if you use 0 as the size in realloc, it will have the same effect as free on some implementations. As Steve Jessop and R.. said in the comments, you shouldn't rely on it.




回答2:


There is definitely not a memory leak, but any of at least 3 things could happen when you call realloc to reduce the size:

  1. The implementation splits the allocated memory block at the new requested length and frees the unused portion at the end.
  2. The implementation makes a new allocation with the new size, copies the old contents to the new location, and frees the entire old allocation.
  3. The implementation does nothing at all.

Option 3 would be a rather bad implementation, but perfectly legal; there's still no "memory leak" because the whole thing will still be freed if you later call free on it.

As for options 1 and 2, which is better depends a lot on whether you favor performance or avoiding memory fragmentation. I believe most real-world implementations will lean towards doing option 1.




回答3:


The new code still leaks the original allocation if the realloc fails. I expect most implementations won't ever fail to shrink a block, but it's allowed. The correct way to call realloc, whether growing or shrinking the block, is void *tmp = realloc(myPointer, 50*sizeof(int)); if (!tmp) { /* handle error somehow. myPointer still points to the old block, which is still allocated */ } myPointer = tmp;. – Steve Jessop 48 mins ago

Hey, I couldn't figure out how to reply to your comment, sorry.

Do I need to cast tmp to the type of myPointer? In this case, do I need to write

myPointer = (int*)tmp

Also, in this case, when I do free(myPointer) The memory pointed at by tmp will be freed as well, right? So no need to do

free(myPointer)
free(tmp)



回答4:


In the way you have given your code, yes, it might have a leak. The idea of realloc is that it can return you a new location of your data. Like you do it in your question you lose that pointer that realloc sends you.

int *myPointer2 = realloc(myPointer,50*sizeof(int));
assert(myPointer2); 
myPointer = myPointer2;


来源:https://stackoverflow.com/questions/7078019/using-realloc-to-shrink-the-allocated-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!