dynamic array -deallocating memory?

Hi i just want to check if ive deleted this array properly, but at the line where it prints arr[2] gives the right value at that location even though I have called delete when i run this. whats going on exactly?!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main(){
  int num;
  cout << "Please enter the number of values wished to be summed." << endl;
  cin >> num;
  int *arr = new int[num];
  int temp = 0;
  
  for(int i =0;i<num;i++){
    cout << "Enter a value:"<<endl;
    cin >> temp;
    arr[i]=temp;
  }
  int total = 0;
  for(int x =0;x<num;x++){
    total+=arr[x];
  }
  delete [] arr;
  cout << arr[2]<<endl;
  cout << "The sum of the values is " << total << endl;
  return 0;
}


...im probably doing something silly >.>
That's what we call undefined behavior, meaning it may give the value that was at the location before you deleted it, it may cause your computer to blow up or maybe pink elephants will surround your house and demand all your peanuts, but usually code like this causes random segmentation faults.


oh okay-but does that mean im correctly deallocating memory then? or should delete get called at the very end?
No it's not correct. You should delete the array after you are finished using it. The program just happens to "work" but there is no real guarantees about what will happen.
Last edited on
so it should be

1
2
3
4
5
6
...
  cout << arr[2]<<endl;
  cout << "The sum of the values is " << total << endl;
  delete [] arr;
  return 0;
}


? for it to be properly deallocated? is there any real way to check this or is it a 'this method should usually work' type thing
Yes that's the way it should be.

You should learn that accessing an object or array after it has been deleted is not allowed, and avoid doing it. In many situations you can avoid the use of new/delete by using a container class. In this case you could have used std::vector<int>.

Your code with std::vector: (notice how similar it is and we don't have to care about delete because the vector will be deallocated automatically when it goes out of scope)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
using namespace std;

int main(){
  int num;
  cout << "Please enter the number of values wished to be summed." << endl;
  cin >> num;
  vector<int> arr(num);
  int temp = 0;
  
  for(int i =0;i<num;i++){
    cout << "Enter a value:"<<endl;
    cin >> temp;
    arr[i]=temp;
  }
  int total = 0;
  for(int x =0;x<num;x++){
    total+=arr[x];
  }
  cout << arr[2]<<endl;
  cout << "The sum of the values is " << total << endl;
  return 0;
}
My apologies for replying back so late, just realized i actually hadn't even though i had read this. Thanks for the help, defs aided my understanding on the matter. :)
Topic archived. No new replies allowed.