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
2009-09-09 18:21:21
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
2009-09-09 18:23:44
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
2009-09-09 18:24:43
still... if you don't need to preserve the data, a free and malloc seems more descriptive of what you are doing.
Toad
2009-09-09 18:35:04
If you don't need to preserve the data, then the cost of copying it anyhow may be prohibitive.
Steven Sudit
2009-09-09 18:37:52
I don't really care about the contents of the memory, FYI.
stanigator
2009-09-10 01:26:51
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
2009-09-10 03:14:10
+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
2009-09-09 18:22:45
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
2009-09-09 18:29:59
I'm sure they meant that they would call malloc, copy stuff over, then free.
Steven Sudit
2009-09-09 18:32:52