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?
enlargeshould probably return a new pointer, and then can be called asx = enlarge(x). Otherwise, you are deleting old memory and leaking new. The caller can no longer access either. Better still, do yourself a favor and usestd::vector<int>void enlarge(std::unique_ptr<int[]> & x) { auto tmp = std::make_unique<int[]>(20); memcpy(tmp.get(), x, 10 * sizeof(int)); x = std::move(tmp); }int main() {auto x = std::make_unique<int[]>(10); enlarge(x);}xby value.void enlarge(int * x) {copies x and enlarges it freeing the original memory location but not changingxin main which after running enlargexinint main()points to the original location which you attempt to free a second time inint main()int x[10]?" -- Inaccurate. Array decay occurs only when you have an object whose type is an array. If you declareint x[10]then the type ofxis an array. If you declareint * xthen the type ofxis a pointer. A pointer cannot be subject to the decay from an array to a pointer because 1) a pointer is not an array and 2) a pointer is already a pointer.