Search code examples
arrayscfunctiondynamic-memory-allocationdynamic-arrays

Use realloc() in function


#include <stdio.h>
#include <stdlib.h>

void Increase(int *array1,int *Nums) {
    int*array2 = realloc(array1,(*Nums+1)*sizeof(int));
    array2[*Nums] = 13;
    array2[*Nums-1] = 14;
    ++(*Nums);
}


int main() {
    int NumOfElements=0,i;
    int*array=(int*)malloc(0*sizeof(int));
    Increase(array,&NumOfElements);
    for(i=0;i<NumOfElements;i++) {
        printf("%d  ", array[i]);
    }
    free(array);
}

How many elements will be in the array in main() if I run this program?

Does the Increase() function increase the number of memory cells of the array in main(), or will the array in main() still just have 0 memory cells?


Solution

  • From the realloc manual page:

    The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails.

    ... so the answer to your question will depend on whether the call to realloc() was able to change the memory-allocation's size in-place, or not.

    If realloc() was able to do an in-place resize (e.g. because the heap had allocated a larger-than-necessary array for the original malloc() call, allowing realloc() to simply mark some of the extra bytes in the buffer as in-use), then realloc() would return the same pointer that was passed in to it as an argument, which is the same memory-location that main() points to via array. In this scenario, main() could access the now-larger-array via array without any problems.

    On the other hand, if realloc() wasn't able to do an in-place resize, then realloc() would be forced to allocate a newer/larger array, copy over the contents of the old array, free() the old array, and return the pointer to the larger array. In that case, array2 would point to a different location in memory than array and array1, and (worse), after Increase() returns, main() would invoke undefined behavior by dereferencing array, which is (at that point) a dangling pointer because realloc() freed the memory it used to point to.