重新分配后,我们是否会丢失缓冲区中的数据? [英] Do we lose data in a buffer after realloc'ing?

查看:124
本文介绍了重新分配后,我们是否会丢失缓冲区中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解重新分配的工作方式时遇到了麻烦.如果我分配了一个缓冲区并将数据复制到该缓冲区,则说"AB":

I'm having troubles understanding how realloc works. If I malloc'ed a buffer and copied data to that buffer, let's say "AB":

 +------------+
 | A | B | \0 |
 +------------+

然后我重新分配了缓冲区,数据中是否会丢失任何数据(甚至是单个字节)?还是只是扩大缓冲区? :

then I realloc'ed the buffer, will there be any lost in the data (even a single byte)?; or it just does expanding the buffer? :

 +------------------------+
 | A | B | \0 | ? | ? | ? |
 +------------------------+

代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

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将保留原始内存块的内容.即使无法调整内存块的大小,旧数据也将被复制到新数据块中.对于减小块大小的realloc,旧数据将被截断.

A realloc that increases the size of the block will retain the contents of the original memory block. Even if the memory block cannot be resized in placed, then the old data will be copied to the new block. For a realloc that reduces the size of the block, the old data will be truncated.

请注意,如果由于某些原因realloc失败,则对realloc的调用将意味着您丢失数据.这是因为realloc不能通过返回NULL失败,但是在那种情况下,原始的内存块仍然有效,但是由于覆盖了指针NULL,您将无法再访问它.

Note that your call to realloc will mean you lose your data if, for some reason the realloc fails. This is because realloc fails by returning NULL, but in that case the original block of memory is still valid but you can't access it any more since you have overwritten the pointer will the NULL.

标准格式为:

newbuffer = realloc(buffer, newsize);
if (newbuffer == NULL)
{
    //handle error
    return ...
}
buffer = newbuffer;

还请注意,在C中不需要强制转换malloc的返回值,并且sizeof(char)根据定义等于1.

Note also that the casting the return value from malloc is unnecessary in C and that sizeof(char) is, by definition, equal to 1.

这篇关于重新分配后,我们是否会丢失缓冲区中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆