使用realloc的缩小分配的内存 [英] Using realloc to shrink the allocated memory

查看:294
本文介绍了使用realloc的缩小分配的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单问题:
如果我使用realloc的收缩是一个指针所指向的内存块,也额外获得的内存释放?还是需要手动释放不知何故?

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?

例如,如果我做

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

我将有一个内存泄漏?

Will I have a memory leak?

推荐答案

没有,你会不会有内存泄漏。 的realloc 只会迎来休息可用为未来的malloc 操作。

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

但你还是得免费 myPointer 以后。顺便说一句,如果你使用 0 的realloc 尺寸,就会产生同样的效果免费对某些实施的。史蒂夫·杰索普和R ..在评论中说,你不应该依赖于它。

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.

这篇关于使用realloc的缩小分配的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆