gpt4 book ai didi

c - 当我重新分配一个更小的缓冲区时,它会删除缓冲区中的数据直到达到正确的大小吗?

转载 作者:行者123 更新时间:2023-12-05 01:19:08 25 4
gpt4 key购买 nike

我的问题有点令人困惑,但我想问的是,realloc 在最小化缓冲区时如何处理剩余数据?例如,假设我有一个充满 50 字节的缓冲区(假设我的缓冲区最多可以容纳 50 字节的数据)。后来在我的代码中,我使用 realloc 调整了我的缓冲区大小,现在最多只能容纳 30 个字节。 realloc 对剩余的 20 多字节做了什么?

最佳答案

realloc 完全是 malloc+memcpy+free,只是有时它设法在 - place 并且它返回的指针在数值上等于您输入的指针(但您永远不能依赖它)。剩余的 20 个字节被释放。

来自C标准,7.22.3.5realloc函数

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. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.

另见 http://en.cppreference.com/w/c/memory/reallochttp://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html

关于c - 当我重新分配一个更小的缓冲区时,它会删除缓冲区中的数据直到达到正确的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41294907/

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