Search code examples
cmallocrealloc

realloc an array with c


I tried to find similar title questions with mine, but I didn't find what I wanted. So here is my question. If I malloc an array with size of 10, is it able to realloc the size and make it 9? And the 8 etc etc ? And if it's able, if I have this array: [1,2,3,4,5,6,7,8,9,10] How can I know which cell will be deleted ? Is it able to choose which one to delete every time ?


Solution

  • When you realloc with a smaller size, many implementation just do nothing: you have a bloc that can hold at least 10 elements, it can hold at least 8 elements. Simply you shall no longer use the elements past the declared size. Nothing will prevent you to do it, but it just invokes Undefined Behaviour.

    It can be surprising for beginners:

    int *arr = malloc(10 * sizeof(int));   // allocate an array of 10 int
    for (int i=0; i<10; i++) {             // initialize it with 0-9
        arr[i] = i;
    }
    arr = realloc(arr, 8*sizeof(int));     // realloc the array to 8 elements
    for (int i=0, i<8; i++) {
        printf(" %d", i);
    }
    printf("\n");                          // should have correctly printed 0 1 ... 7
    // the interesting part
    for (int i=8; i<10; i++) {
        printf(" %d", i);                  // Oops, UB!
    }
    printf("\n");                          // but what is to be expected is just 8 9...
    

    Now it works but is UB. Say differently never pretend that I said that it was correct code. But most implementations will accept it and will give the expected result (which is allowed by UB...) without any other side effect.