We already saw how to manage pointers to a resource in the Managing pointers to classes that do not leave scope recipe. But, when we deal with arrays, we need to call delete[]
instead of a simple delete
. Otherwise, there will be a memory leak. Take a look at the following code:
void may_throw1(char ch); void may_throw2(const char* buffer); void foo() { // we cannot allocate 10MB of memory on stack, // so we allocate it on heap char* buffer = new char[1024 * 1024 * 10]; // Oops. Here comes some code, that may throw. // It was a bad idea to use raw pointer as the memory may leak!! may_throw1(buffer[0]); may_throw2(buffer); delete[] buffer; }