views:

539

answers:

3

Why would one use realloc() function to resize an dynamically allocated array rather than using free() function before calling the malloc() function again (i.e. pros and cons, advantages vs. disadvantages, etc.)? It's for C programming, but I can't find the proper tag for it. Thanks in advance.

+9  A: 

The advantage is that realloc will preserve the contents of the memory. With free + malloc you'd need to reset the data in the array.

JaredPar
which is also the disadvantage. If you're not interested in data preservation, doing the free and malloc might be faster in some cases (where the memory block needs to be moved because of the size growth)
Toad
It's faster to realloc down, and might be faster to realloc up if there's room to grow in place. Otherwise, it translates to a malloc/copy/free.
Steven Sudit
still... if you don't need to preserve the data, a free and malloc seems more descriptive of what you are doing.
Toad
If you don't need to preserve the data, then the cost of copying it anyhow may be prohibitive.
Steven Sudit
I don't really care about the contents of the memory, FYI.
stanigator
Then free the old buffer and malloc the new buffer, in that order. Any decent implementation of malloc() will handle that efficiently. Trying to optimize such a situation through the use of realloc() will ultimately be a lose.
bbum
+2  A: 

Well, realloc may change the size of the block in place, or allocate a new one and copy as much as will fit. In contrast, malloc and free together can only allocate a new one, and you have to do your own copying.

To be frank, realloc doesn't get as much use these days because it doesn't work well with C++. As a result, there's been a tendency for memory managers not to optimize for it.

Steven Sudit
A: 

"rather than using free() function before calling the malloc() function again"

If you free the existing array, you've lost all of its contents, so you cannot "grow" the array in the usual sense.

me22
I'm sure they meant that they would call malloc, copy stuff over, then free.
Steven Sudit
Steven just said what I meant.
stanigator