c++pointersdynamic-memory-allocationdelete-operatorpass-by-value

How to delete[] decayed array?


How to delete an array declared with new if I don't have access to the original pointer x? Let's assume, I know the array size.

For example, if I write the following code:

void enlarge(int * x) {
    int * tmp = new int[20];
    memcpy(tmp, x, 10*sizeof(int));
    delete[] x; //?
    x = tmp;
}

int main() {
    int * x = new int[10];
    enlarge(x);
    delete[] x; //??? free(): double free detected in tcache 2
}
  1. Would delete[] within enlarge() function know how much memory to free?
  2. Apparently, delete[] within main() results in an error during execution. Why? How to avoid it?

Solution

  • The function enlarge produces a memory leak because the pointer x declared in main is passed to the function by value. That is the function deals with a copy of the value of the original pointer x. Changing within the function the copy leaves the original pointer x declared in main unchanged.

    As a result this statement in main

    delete[] x;
    

    invokes undefined behavior because the memory pointed to by the pointer x was already freed in the function enlarge.

    You need to pass the pointer by reference like

    void enlarge(int * &x) {
        int * tmp = new int[20];
        memcpy(tmp, x, 10*sizeof(int));
        delete[] x;
        x = tmp;
    }
    

    Pay attention to that instead of raw pointers it is better to use standard container std::vector.