可以realloc的移动指针,如果新的大小? [英] can realloc move pointer if new size smaller?
问题描述
我想知道是否C或C ++标准的保证,当realloc的是带一个小的(非零)尺寸的指针没有改变:
I am wondering whether the C or C++ standard guarantees that a pointer is not changed when realloc is called with a smaller (nonzero) size:
size_t n=1000;
T*ptr=(T*)malloc(n*sizeof(T));
//<--do something useful (that won't touch/reallocate ptr of course)
size_t n2=100;//or any value in [1,n-1]
T*ptr2=(T*)realloc(ptr,n2*sizeof(T));
//<-- are we guaranteed that ptr2==ptr ?
基本上,可以在操作系统上了自己的决定,因为我们释放了大量的内存块,他要充分利用一切reallocs的整理内存,并以某种方式移动PTR2?
Basically, can the OS decide on its own that since we freed a large memory block, he wants to take advantage of all reallocs to defragment the memory, and somehow move ptr2 ?
推荐答案
<一个href=\"http://opengroup.org/onlinepubs/007908775/xsh/realloc.html\">http://opengroup.org/onlinepubs/007908775/xsh/realloc.html
当与一个大小不等于0成功完成,realloc()的指针返回到(可能移动)分配的空间。
Upon successful completion with a size not equal to 0, realloc() returns a pointer to the (possibly moved) allocated space.
不,不能保证
这篇关于可以realloc的移动指针,如果新的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!