Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do realloc and memcpy work?

I have two questions.

  1. Do realloc() and memcpy() copy the entries in an array to another in a way faster than just iterating on each element O(N) ? If the answer is yes then what do you think is its complexity ?

  2. If the size allocated is smaller than the original size, does realloc() copy the entries to somewhere else or just leave them as they are decreasing the size of the array ?

like image 255
Ahmed Mounir Avatar asked Dec 12 '08 13:12

Ahmed Mounir


People also ask

Does realloc use memcpy?

If you have references to structures allocated by malloc, these references can now be bogus since realloc is free to move where it reallocates your memory. In other words, it can do the equivalent of a malloc, memcpy of your data to a new location then it frees your old memory.

How memcpy function works?

memcpy() function in C/C++ The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string. h” header file in C language.

How does realloc work in C++?

C++ realloc() The realloc() function in C++ reallocates a block of memory that was previously allocated but not yet freed. The realloc() function reallocates memory that was previously allocated using malloc(), calloc() or realloc() function and yet not freed using the free() function.

Does memcpy call malloc?

No memcpy does not use malloc .


1 Answers

1 - No. They copy a block at a time. See http://www.embedded.com/design/configurable-systems/4024961/Optimizing-Memcpy-improves-speed for a pretty good analysis.

2 - This is implementation dependent. See http://www.gnu.org/software/libtool/manual/libc/Changing-Block-Size.html for glibc details. "In several allocation implementations, making a block smaller sometimes necessitates copying it"

like image 199
Sean Avatar answered Sep 22 '22 11:09

Sean