我很难理解realloc是如何工作的。 如果我malloc’ed缓冲区并将数据复制到该缓冲区,让我们说“AB”:
+------------+ | A | B | | +------------+
然后我重新分配了缓冲区,数据中是否会丢失(甚至是单个字节)? 或者只是扩展缓冲区? :
+------------------------+ | A | B | | ? | ? | ? | +------------------------+
码:
#include #include #include int main(void){ char* buffer = (char*) malloc( sizeof(char) * 3 ); strncpy(buffer, "AB", 2); buffer = (char*) realloc(buffer, sizeof(char) * 6); /* Will there be any lost here? */ free(buffer); return(0); }
增加块大小的realloc
将保留原始内存块的内容。 即使内存块无法在放置中resize,也会将旧数据复制到新块中。 对于减少块大小的realloc
,旧数据将被截断。
请注意,如果由于某种原因realloc
失败,则对realloc
的调用将意味着您丢失了数据。 这是因为realloc
通过返回NULL
失败,但在这种情况下,原始内存块仍然有效,但由于您已覆盖指针,因此无法再访问它。
标准模式是:
newbuffer = realloc(buffer, newsize); if (newbuffer == NULL) { //handle error return ... } buffer = newbuffer;
另请注意,在C中不需要从malloc
转换返回值,并且sizeof(char)
根据定义等于1
。
什么都没有丢失。 但你真的应该测试realloc()
(以及之前的malloc()
)是否“有效”。
同样,对malloc的返回值的强制转换最多也是多余的,并且它可能隐藏编译器在其缺失时将捕获的错误。
基于您想要字符串的假设,您对strncpy
的使用是错误的
需要了解更多c/c++开发分享重新分配后,我们是否会在缓冲区中丢失数据?,也可以关注C/ C++技术分享栏目—计算机技术网(www.ctvol.com)!
#include #include #include int main(void) { char *buffer = malloc(3); if (buffer == NULL) /* no memory */ exit(EXIT_FAILURE); strncpy(buffer, "AB", 2); /* ATTENTTION! ATTENTION: your array is not a string. ** buffer[2] is not the zero string terminator */ // buffer = realloc(buffer, 6); /* Will there be any lost here? */ /* If realloc returns NULL, you've just lost the only pointer to ** the allocalted memory, by overwriting it with NULL. ** Always `realloc` to a temporary variable */ char *tmp_buffer = realloc(buffer, 6); if (tmp_buffer == NULL) { /* realloc failed */ } else { /* realloc worked, no bytes lost */ buffer = tmp_buffer; /* ATTENTION! ATTENTION: buffer is still not a string ** buffer[0] is 'A', buffer[1] is 'B', ** all other elements of buffer are indeterminate */ } free(buffer); return(0); }
以上就是c/c++开发分享重新分配后,我们是否会在缓冲区中丢失数据?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/980498.html