我可以假设调用realloc的非常小的尺寸将释放其余的? [英] Can I assume that calling realloc with a smaller size will free the remainder?
问题描述
让我们考虑一下这个很短的code的片段:
的#include<&stdlib.h中GT;诠释的main()
{
字符* A =的malloc(20000);
字符* B = realloc的(一,5); 免费(B);
返回0;
}
阅读手册页的realloc后,我不能完全肯定,第二行会造成19995额外的字节被释放。引述手册页:的realloc()的函数改变内存块的大小由ptr大小字节
,但是从这个定义,我可以肯定的。其余部分将被释放?
我的意思是,由指出b
块肯定包含5个免费字节,所以它会为一个懒惰相符分配器只是没有做的realloc的线什么就够了吗?
请注意:我使用的分配似乎释放19 995额外的字节,作为注释掉时,所示的valgrind的免费(B)
行:
== == 4457 HEAP摘要:
== == 4457使用在出口处:在1块5个字节
== == 4457总堆的使用情况:2 allocs,1的FreeS,2万5字节分配
是由C标准保证,如果新的对象可以进行分配。
(C99,7.20.3.4p2)的realloc函数将释放旧的对象ptr指向并返回一个指针,指向具有由size指定一个新的对象。
块引用>Let’s consider this very short snippet of code:
#include <stdlib.h> int main() { char* a = malloc(20000); char* b = realloc(a, 5); free(b); return 0; }
After reading the man page for realloc, I was not entirely sure that the second line would cause the 19995 extra bytes to be freed. To quote the man page:
The realloc() function changes the size of the memory block pointed to by ptr to size bytes.
, but from that definition, can I be sure the rest will be freed?I mean, the block pointed by
b
certainly contains 5 free bytes, so would it be enough for a lazy complying allocator to just not do anything for the realloc line?Note: The allocator I use seems to free the 19 995 extra bytes, as shown by valgrind when commenting out the
free(b)
line :==4457== HEAP SUMMARY: ==4457== in use at exit: 5 bytes in 1 blocks ==4457== total heap usage: 2 allocs, 1 frees, 20,005 bytes allocated
解决方案Yes, guaranteed by the C Standard if the new object can be allocated.
(C99, 7.20.3.4p2) "The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size."
这篇关于我可以假设调用realloc的非常小的尺寸将释放其余的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!