Search code examples
carraysdynamicmallocrealloc

Is it a good way to take an unkown-size array with using realloc many times


I will read a file which has an array with unknown-size like that

1, 2, 3, ....

5, 6, 8 ....

Is that algorithm safe and fast to use ?

 array =NULL;    /* for realloc */
for(i=0;fgets(line,256,input) != NULL ;++i){
    array =(double**)realloc(array,sizeof(double*)*(i+1));
    value =strtok(line,selector); 
    for(j=0;value != NULL;++j){

        array[i] =(double*)realloc(array[i],sizeof(double)*(j+1));
        sscanf(value,"%lf",&array[i][j]);
        value =strtok(NULL,selector);
    }

}

Solution

  • On the speed: Your algorithm has quadratic complexity O(n^2), where n is the number of values per line or the number of lines. This is not efficient.

    The normal workaround for this is, to keep track of two sizes, the size of the allocated array, and the number of elements that are currently in use. A value is added either by just incrementing the number of elements in current use (and storing the value at the correct location, of course), or by first realloc()ing the array to twice the current size. The result of this is, that even when n is very large, the average element in the array is copied only once. This brings the complexity down to O(n).

    Of course, all of this is irrelevant if you only ever have something like ten entries in your arrays. But you were asking for speed.


    On the safety: The only risk that I see is that you are fragmenting your address space more than necessary by creating tons of temporary objects which are just created to be replaced by a slightly larger one in the next iteration. This may lead to increased memory hunger in the long run, but it's virtually impossible to gauge this effect precisely.