gpt4 book ai didi

如果新尺寸更小,realloc 可以移动指针吗?

转载 作者:太空狗 更新时间:2023-10-29 16:42:20 26 4
gpt4 key购买 nike

我想知道 C 或 C++ 标准是否保证在以较小(非零)大小调用 realloc 时指针不会更改:

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 ?

最佳答案

http://opengroup.org/onlinepubs/007908775/xsh/realloc.html

Upon successful completion with a size not equal to 0, realloc() returns a pointer to the (possibly moved) allocated space.

不,不保证

关于如果新尺寸更小,realloc 可以移动指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com