0

I created a Vector class containing an array (stored in a heap) and an integer n_rows counting the amount of elements inside the array. In order to delete the array properly during the instance destruction I used the delete as explained here.

Class (in header file):

private:
    int n_rows;
    int* vect;

public:
    Vector(int);
    ~Vector();
    std::string toString(); // returns elements from vect

Destructor (in .cpp):

Vector::~Vector(){
    delete [] this->vect;
    cout << this->toString() << endl;
}

However if I print the array vect after deleting it, seemingly just the first two entries get deleted.

Example:

// Vector:
[2 2 2 2 2 2]

// Destruction
[0 0 2 2 2 2]

My questions: Is this resource properly deleted? Why does it just appear that the two first elements get modified?

Blaze
  • 16,736
  • 2
  • 25
  • 44
Pablo Jeken Rico
  • 569
  • 5
  • 22
  • Same explanation given [here](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794). – StoryTeller - Unslander Monica Oct 08 '18 at 09:17
  • After doing `delete [] this->vect`, any usage of `this->vect` (including in `toString()`) has undefined behaviour. Any behaviour is permitted, whether you expect it or not. – Peter Oct 08 '18 at 09:26
  • The duplicate is not 100% (this question here doesn't reallocate the memory first - not that it's any more or less UB), but there is in-depth elaboration there on "but why does it change the first two elements and not the next ones?". – Max Langhof Oct 08 '18 at 09:27

2 Answers2

3

Your destructor free the memory pointed to by vect, but it doesn't do anything to the contents of that memory.

Dereferencing an invalid pointer (like the one you have after doing delete[] on it) leads to undefined behavior. Just don't do it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

The memory is freed up when you delete it, but it's not necessarily overwritten/set to zero or anything like that. Accessing the freed memory is undefined behavior and anything might happen, but what often happens (and happened in this case) is that you get the old values that were there before it was deleted. In other words, when it is deleted, it is mostly just "marked for being available again".

The program usually won't waste time writing over the deleted memory. If the memory is reassigned, then whatever is getting the memory will most likely initialize it however it wants anyway.

Blaze
  • 16,736
  • 2
  • 25
  • 44