Search code examples
carraysmallocrealloc

c, shrink allocated space from the beginning


Assume I have allocated space for an array with

double *array;
array=malloc(100*sizeof(double));

I do some processes and finally I don't need the first 10 elements any more, I tried this with realloc:

array=realloc(array+10, 90*sizeof(double));

but I get an invalid pointer error:

*** glibc detected *** ./temp: realloc(): invalid pointer:...

How can I shrink an array from its beginning?


Solution

  • Firstly, reallocating an array just in order to shrink it is not quite a good idea. If you do it a lot of times, it may potentially lead to memory fragmentation. Use realloc() to extend the array when necessary. (This won't prevent fragmentation either of course, but if you use realloc() less, that helps.)


    That said, if you still want to shrink the array: as the documentation (which you have read before asking this question, amirite?) says, you have to call realloc() on the pointer returned by malloc(). Not that pointer plus ten, not that pointer times Euler's constant, not that pointer minus the number of days in the current month, nothing else, just that very same pointer.

    So you have to move the elements first, then reallocate the array. But that involves copying the elements to a temporary buffer like this:

    double *tmp = malloc(90 * sizeof(*tmp));
    memcpy(tmp, array, 90 * sizeof(*tmp));
    
    double *guard = realloc(array, 90 * sizeof(*array));
    if (!guard) {
        // realloc() failed
        abort(); // whatever
    }
    
    array = guard;
    memcpy(array, tmp, 90 * sizeof(*tmp));
    

    So this isn't any better, you could just free() the old array after copying its contents and assigning the newly obtained pointer to array.