0

This might be a very trivial question but why am I still able to access the values from the array(which was dynamically allocated) even after using the delete keyword.

#include <iostream>
using namespace std;

int main(){
    #ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        freopen("output.txt","w",stdout);
        freopen("error.txt","w",stderr);
    #endif

    int *arr = new int[10];
    for(int i=0;i<10;i++){
        arr[i] = i+1;

    }

    for(int i=0;i<10;i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;

    delete[] arr;

    for(int i=0;i<10;i++){

        cout << arr[i] << " ";
    }

    return 0;
}

What i know is that using the delete keyword frees the memory which was allocated.

I am pretty new to C++. Any help would be appreciated.

  • 2
    Undefined behavior, anything can happen. See [here](https://stackoverflow.com/a/72395390/12002570) for example. – Jason Jul 12 '22 at 12:56
  • @pptaszni so this is not a concept it is just some undefined behaviour? – Abhishek jha Jul 12 '22 at 12:58
  • Undefined behavior means anything could happen as also explained [here](https://stackoverflow.com/a/72395390/12002570) – Jason Jul 12 '22 at 13:00
  • 2
    When you delete `arr` the memory allocated to the array doesn't cease to exist its just marked as available for re-use, therefore there is a chance (especially just after `delete` in a single threaded program) that the array will continue to be accessible. This is completely undefined behaviour though, it might "work" one time you run the program but crash the next – Alan Birtles Jul 12 '22 at 13:03
  • @AlanBirtles this is probably a better explanation. I thought that using `delete` frees the memory and memory would not be accessible. – Abhishek jha Jul 12 '22 at 13:08
  • 1
    ***I thought that using delete frees the memory and memory would not be accessible***The reason for this behavior is your c++ memory management typically allocates blocks of memory from your OS in pages. These pages are usually a few KB. Perhaps something else is in the page so the whole page can't be given back to the OS. Also even if that was not the case your c++ memory management may not give the memory back immediately to your OS because this OS operation is time consuming and perhaps your application will soon allocate another memory block.. – drescherjm Jul 12 '22 at 13:24

0 Answers0