1

I'm learning C++ from Stroustrop's A Tour of C++ 2E and I'm playing around with his examples.

I have a struct Vector, with a member elements that is a pointer to an array of doubles. I'm trying to delete[] the array which I allocated with new[], but even if there are no compile- or run-time errors, the array does not seem to be getting deleted. What's going on here?

#include <iostream>

struct Vector {
  int size;
  double* elements;
};

void print_array(double* first, int size) {
  double* cursor = first;
  for (int i = 0; i < size; ++i) {
    std::cout << *cursor << " ";
    ++cursor;
  }
  std::cout << "\n";
}

int main() {
  Vector v;
  v.size = 5;
  v.elements = new double[5];
  
  for (int i = 0; i < v.size; ++i) {
    v.elements[i] = 9-i;
  }
  print_array(v.elements, v.size);
  
  delete[] v.elements;
  std::cout << "v.elements==nullptr ? " << (v.elements==nullptr) << "\n";
  print_array(v.elements, v.size);
  
  return 0;
}

The output I'm getting is:

9 8 7 6 5 
v.elements==nullptr ? 0
9 8 7 6 5 

I do not yet know what will happen if I print out a deleted array, but I'm baffled as to why the third line in the output is happening at all. Thanks in advance.

Matthew Quiros
  • 13,385
  • 12
  • 87
  • 132
  • `delete` doesn't automatically set pointer to nullptr. – Louis Go Aug 20 '20 at 06:32
  • 1
    Delete does not "delete" your memory, it simply returns it to the heap, the old data is not re-written unless something else uses it. – Moshe Gottlieb Aug 20 '20 at 06:32
  • 1
    @Slava none of tag OP has is C++ related. – Louis Go Aug 20 '20 at 06:33
  • Though question is not exactly the same, read the answer about "hotel room". It very well describes what is going on. No it means at least you are familiar with rules. For example that SO is not a replacement for a textbook. – Slava Aug 20 '20 at 06:35
  • @Slava would you mind to add link of the answer about "hotel room" in comment? – Louis Go Aug 20 '20 at 06:36
  • 1
    Here is the link https://stackoverflow.com/a/6445794/432358 you can also reach it easily if you click on the duplicate. – Slava Aug 20 '20 at 06:37
  • Also added direct duplicate to your question, you are welcome. – Slava Aug 20 '20 at 06:41
  • 1
    Sorry looks like I overreacted as there are too many people who completely ignore rules when asking questions. Anyway your question is already answered before. I do recommend to read answer about "hotel room" it should remove many misunderstandings you could get later. Unfortunately in C++ even if you get expected output does not mean your program works. – Slava Aug 20 '20 at 06:45

0 Answers0