How does realloc know how much to copy?

后端 未结 5 1100
庸人自扰
庸人自扰 2020-12-11 15:52

how does realloc know the size of original data?

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

So, if the implementation is like this:

         


        
5条回答
  •  我在风中等你
    2020-12-11 16:39

    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.

提交回复
热议问题