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.