Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does realloc know how much to copy?

Tags:

c

realloc

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/..?

like image 871
Rok Povsic Avatar asked Aug 13 '10 11:08

Rok Povsic


People also ask

How does realloc know size?

Size of dynamically allocated memory can be changed by using realloc(). As per the C99 standard: void * realloc ( void *ptr, size_t size); realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size.

Does realloc copy content?

The realloc function allocates a block of memory (which be can make it larger or smaller in size than the original) and copies the contents of the old block to the new block of memory, if necessary.

How does realloc ptr size?

The realloc() function changes the size of a previously reserved storage block. The ptr argument points to the beginning of the block. The size argument gives the new size of the block, in bytes. The contents of the block are unchanged up to the shorter of the new and old sizes.

Does realloc delete old data?

The realloc() function reallocates memory that was previously allocated using malloc(), calloc() or realloc() function and yet not freed using the free() function. If the new size is zero, the value returned depends on the implementation of the library. It may or may not return a null pointer.


1 Answers

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.

like image 155
David Avatar answered Sep 29 '22 10:09

David