3

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 :

0
1
4
9
16
4

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 ?

rpanske
  • 125
  • 1
  • 2
  • 10
  • 2
    [Yes and it is called *undefined behavior*](http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a) – Rakete1111 Aug 28 '16 at 07:15
  • 2
    They will retain their values until another process writes to them. Reading them after `delete` is *undefined behaviour*, which includes their values still being valid. – Weather Vane Aug 28 '16 at 07:15
  • Your code has a bug. Fix the bug and the mystery will go away. Yes, code with bugs will not do what you expect it to do. That's why we fix bugs when we discover them. – David Schwartz Aug 28 '16 at 07:32
  • 1
    You added a **really bad** answer to your question. Please don't do that. If you like an answer, upvote it or select it, but don't vandalize the question. – David Schwartz Aug 28 '16 at 07:58
  • Sorry I'm new here and I thought it would help others – rpanske Aug 28 '16 at 08:01
  • @rpanske You posted C++ code, not `C`. Remove the `C` tag. – PaulMcKenzie Aug 28 '16 at 08:05

1 Answers1

4

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.

Peter
  • 35,646
  • 4
  • 32
  • 74