如何realloc的知道多少复制? [英] How does realloc know how much to copy?

查看:177
本文介绍了如何realloc的知道多少复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何做的realloc知道原始数据的大小?

 的void * realloc的(无效* PTR,为size_t大小);

所以,如果实现是这样的:

  TEMP =的malloc(大小);
 的memcpy(.. //多少复制?
 免费(PTR);
 返回温度;

我知道这是不是原来的执行和realloc并不总是做免费的,但如果这样做,需要多少复制?

编辑:
感谢您的答案。但是,我怎么能那么实现我的code使用malloc /免费/..?

解决方案

据了解,因为的malloc 信息的记录,当你把它叫做。毕竟,该系统具有跟踪分配的块的大小的反正以便它不分配的存储器的特定区域的两倍。

如果你的意思是,它是如何知道多少我已经写在迄今为止阵,它并不需要。它可以复制任何未初始化的垃圾也是如此。

how does realloc know the size of original data?

 void *realloc(void *ptr, size_t size);

So, if the implementation is like this:

 temp = malloc(size);
 memcpy(.. // How much to copy?
 free(ptr);
 return temp;

I realize this is not the original implementation, and realloc doesn't always do free, but when it does, how much does it copy?

Edit: Thanks for the answers. But how can I then implement realloc in my code with malloc/free/..?

解决方案

It knows because malloc recorded that information when you called it. After all, the system has to keep track of the sizes of allocated blocks anyway so that it doesn't allocate a particular region of memory twice.

If you mean, "how does it know how much of the array I've written in so far", it doesn't need to. It can just copy any uninitialised garbage as well.

这篇关于如何realloc的知道多少复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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