Блог пользователя ankit_gupta_

Автор ankit_gupta_, история, 8 лет назад, По-английски

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?

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
8 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Because arr still exists in a memory as a dangling pointer. After delete[] arr you also need to write arr = NULL. Check here

»
8 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

It is undefined behavior. It sure gives Runtime Error on the CodeForces' custom invocation. Try it out

»
8 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

You're trying to access currently unallocated memory. This is undefined behaviour. It might work, or it might crash your computer. Simply: don't do it.

»
8 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +3 Проголосовать: не нравится

ar = new int[15] — "Yo, dog, I wanna 15 * sizeof(int) bytes. Give me that and we're both be cool". OS gives you 15 * sizeof(int) bytes. You can access that bytes and no one other shouldn't access same bytes (keyword here is "shouldn't". Another program can access any of byte, but this can lead it to Segmentation Fault. Another thread of same process can access any of byte, but this lead to UB).

delete ar[] — "Thanks there's no need of that bytes. Take it away". OS marks this bytes as free bytes (not modify). And that's all.

Free and allocated bytes both exists regarless of new, delete operators. Even regardless of processes. On C++ there is one rule — use only bytes you allocated. Otherwise you can get UB or SF.