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?
Because arr still exists in a memory as a dangling pointer. After
delete[] arr
you also need to writearr = NULL
. Check herearr = NULL is not helping, it just makes the array pointer points to NULL with which we cannot use [] operator, e.g try arr = NULL just after memory allocation.
Sorry, but I don't understand your point. Why would you write that after memory allocation? Your task is to delete the pointer to the array, right? There is only this thing: When we write
delete[]
for freeing memory it doesn't actually wipes it out. It creates a dangling pointer which we need to point to NULL. Anyway, here is what you said. It still gives a runtime error.It is UB. The same ideone gives "Success" here
Sure it is. But you can see that in custom invocation as well, it gives right output and then terminates with runtime error. That's what I want to tell. Even if we use
delete[]
it still is accessible that's why printing right output.runtime error is not because it removes the dangling pointer, it just changes the object arr points to and the new object do not have [] operator defined.
It is undefined behavior. It sure gives Runtime Error on the CodeForces' custom invocation. Try it out
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.
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.