Memcpy
Memcpy() is a C standard library function used for copying a block of memory bytes from one place to another.
Realloc
C library function for reallocating a dynamically allocated memory region.
Others
Example |
---|
As we can see copying manually with memcpy is always slower than realloc because in this scenario malloc is guaranteed to allocate new memory and you re forced to copy the data in every allocation which shows us that realloc is indeed reusing the same address and enlarging the block size in some cases from question Differences between using realloc vs. free -> malloc functions |
As you can see from the above tests realloc is consistently faster compared to memalloc memcpy and free from question C++/ActiveX replacing realloc with malloc, memcpy, free. Functional and Performance tests |
Calling it twice for contraction and expansion or calling malloc-new memcpy free-old is very unlikely to be as efficient though as with all optimisations you should measure don t guess;keep in mind that realloc doesn t necessarily have to copy your memory at all from question Realloc but only first few bytes is meaningful |