Memory allocation and deallocation

Revision en2, by ankit_gupta_, 2018-11-22 10:41:16

In the code:

#include <bits/stdc++.h>
using namespace std;
int main() {
  int *arr = new int[15];

  for (int i = 0; i < 5; i++)
    arr[i] = 2 * i;

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

  delete[] arr;

  for (int i = 0; i < 5; i++)
    arr[i] = 3 * i + 1;

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

  return 0;
}

Output:

0 2 4 6 8

1 4 7 10 13

i.e. there is no error

How are we able to access and modify an array which does not exist in the memory? Edit: What is the lifetime of the above array? is it till delete operation or ending curly parenthesis?

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English ankit_gupta_ 2018-11-22 10:41:16 110
en1 English ankit_gupta_ 2018-11-22 09:12:21 610 Initial revision (published)