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?
The function
enlargeproduces a memory leak because the pointerxdeclared in main is passed to the function by value. That is the function deals with a copy of the value of the original pointerx. Changing within the function the copy leaves the original pointerxdeclared in main unchanged.As a result this statement in main
invokes undefined behavior because the memory pointed to by the pointer
xwas already freed in the functionenlarge.You need to pass the pointer by reference like
Pay attention to that instead of raw pointers it is better to use standard container
std::vector.