Code:
int build (FILE *fp, COLOR **ppcolor)
{
int size = 0;
*ppcolor = (COLOR *) malloc (sizeof (COLOR));
while (fread (*ppcolor + size, sizeof (COLOR), 1, fp) == 1)
{
size++;
*ppcolor = realloc (*ppcolor, (size + 1) * sizeof (COLOR));
} /* while */
return size;
} /* build */
With function build() I intend to create an array of structures (of type COLOR) which starts at memory location *ppcolor. Data are read from binary file fp (full of COLOR structures).
This works fine. I am just not satisfied with this code. Realloc is inside a loop which may take up to 1.000.000 iterations. I know realloc() may move the whole allocated memory block if there's no enough space for the new incoming elements, so this function could be moving increasingly larger blocks of memory for each iteration !!
I hope you get my point.
Any help appreciated !