Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete[] decayed array? [duplicate]

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?
like image 455
user1079505 Avatar asked Oct 16 '25 01:10

user1079505


1 Answers

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.

like image 79
Vlad from Moscow Avatar answered Oct 18 '25 15:10

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!