本文介绍了为什么在没有复制数据的情况下标准C库中没有像realloc()这样的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想要这样的功能:

For example, I want such a function:

char *dst = (char*)malloc(512);
char *src = (char*)malloc(1024);
...
dst = (char*)realloc(dst, 1024);
memcpy(dst, src, 1024);

如您所见,我只希望函数realloc()扩展缓冲区的大小,但是C库中的realloc()可能会从旧地址复制数据.那么像我想要的任何库中都有一个函数吗?

As you see, I just want the function realloc() to extend the size of buffer, but the realloc() in C library may copy data from old address. So is there a function in any library like what I want?

推荐答案

realloc尝试在不复制的情况下扩展了缓冲区,但是只有在多余的空间可用的情况下才能这样做.

realloc attempts do extend the buffer without copying, but can only do that if the extra space is free.

在您的情况下,您只是为src分配了空间,而该内存块可能已经使用了realloc所需的空间.在这种情况下,它只能在其他地方分配更大的块,然后将数据复制到该块.

In your case, you just allocated space for src and that memory block just might have used the space realloc would have needed. In that case it can only allocate a larger block somewhere else and copy the data to that block.

这篇关于为什么在没有复制数据的情况下标准C库中没有像realloc()这样的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:15