rpanske rpanske - 1 month ago 6x
C++ Question

Release memory from C-Style-Array

I've written a short code to get an idea about C-style arrays created by raw pointers. I know its unusual to use this method today, but I just want to try it out. So here is my code :

#include <iostream>

int main() {
int *ptr = new int[5];
for(unsigned int counter = 0; counter < 5; counter++) {
ptr[counter] = counter * counter;
std::cout << ptr[counter] << std::endl;

delete [] ptr;

std::cout << ptr[2] << std::endl; // Contains still a value

Output :


Its a very simple code, I've just created a memory field of five "int" characters and fill these with some numbers. I delete the array-pointer construct after usage to avoid memory leaks, but to my surprise contains the third to the fith position still values, the first and the second pointer were deleted correctly. Does anyone have an answer for this phenomenon ?


Once the statement delete [] ptr is completed, almost any usage of ptr (other than reassigning it to point at something) gives undefined behaviour.

The meaning of "undefined", in the C++ standard, is that the standard doesn't specify any constraints or requirements on what happens. So, with one implementation (compiler and library) it might give the results you see. With another it can terminate the program abnormally. With yet another implementation, the observed behaviour could be different every time the program is run. All of those possibilities, and others, are correct because the standard does not describe any requirements.

In your particular case, it simply means that the working of operator delete [] provided by your implementation does not overwrite the memory, and does not prevent your program from subsequently accessing that memory. However, you might (or might not) find that a series of other operations (e.g. allocating another array) could suddenly change the results you see.