Afficher un message
Vieux 19/10/2007, 15h02   #8
Kenneth Brody
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Is realloc good form ?

Guillaume Dargaud wrote:
>
> Hello all,
> I have a 'good practice' question.
> Lately I've been using a lot of functions such as this:
>
> void Func(int Size, double *Array) {
> static double *Transformed=NULL;
> Transformed=realloc(Transformed, Size*sizeof(double));
> // Do something from Array to Transformed
> }
>
> Now if the value of Size changes a lot between calls, the resulting prog is
> poorly optimized (it reallocates each time). I'm ok with that.
> Ignoring the fact that the memory is never freed, if the value of Size
> changes seldom, does the call to realloc wastes time then ?


I would suspect that any decent realloc() would, once it sees that
the old size and new size are identical, simply return the current
pointer. (It must determine the old size at some point, in order
to perform its duties. Even a suboptimal "call malloc, memcpy the
buffer, and then free the original" routine needs to know the old
size.)

If you're that concerned, you can always keep track of the old size,
and skip the realloc() if it didn't change:

void Func(int Size, double *Array)
{
static double *Transformed = NULL;
static int OldSize = 0;

ASSERT( Size != 0 ); /* What do we want to do about zero size? */

if ( Size != OldSize )
{
Transformed = realloc(Transformed, Size*sizeof(*Transformed));
OldSize = Size;
}

/* Do something from Array to Transformed */

}

If you're not concerned about "wasted memory", you could even
change the realloc-condition to:

if ( Size > OldSize )

Then, it will only realloc if the buffer needs to grow.

Finally, if you don't need the current contents of Transformed,
it may be more efficient to call free/malloc instead, as this
skips the copy.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:ThisIsASpamTrap@gmail.com>


  Réponse avec citation
 
Page generated in 0,05555 seconds with 9 queries