使用 realloc 缩小分配的内存 [英] Using realloc to shrink the allocated memory
问题描述
关于C中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);
我会出现内存泄漏吗?
推荐答案
不,您不会有内存泄漏.realloc
将简单地将其余的标记为可用"以供将来的 malloc
操作使用.
No, you won't have a memory leak. realloc
will simply mark the rest "available" for future malloc
operations.
但是你以后仍然需要free
myPointer
.顺便说一句,如果您在 realloc
中使用 0
作为大小,它将与 free
在某些实现中具有相同的效果.正如 Steve Jessop 和 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屋!