Afficher un message
Vieux 18/10/2007, 11h28   #2
christian.bau
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Is realloc good form ?

On Oct 18, 10:02 am, "Guillaume Dargaud"
<use_the_form_on_my_contact_p...@www.gdargaud.ne t> 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 ?


It depends. realloc will often be clever enough to realise that it can
just use the previous block of data without any change. So if you pass
in the same Size or similar Size values (like 10000, 10001, 9999) it
will be fast. However, if a new block is allocated, all the data will
be copied from the previous block to the new block, because that is
what realloc does. That might be quite wasteful.

You might just add another variable "static int allocatedSize = 0",
compare new and old size and only realloc when it gets bigger.

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