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
}
- Would
delete[]
withinenlarge()
function know how much memory to free? - Apparently,
delete[]
withinmain()
results in an error during execution. Why? How to avoid it?