+ 2

How new and delete operator working?

# In this program i created pointer for an array and an integer. # after i use the delete operator to deallocte the memory, it gives the same output which is already in that position. # Why? https://code.sololearn.com/cGUpGbfpQ0uK/?ref=app

19th Feb 2021, 1:43 AM
Jawahirullah
Jawahirullah - avatar
2 odpowiedzi
+ 6
M. Jawahirullah all the `delete` operator does is call the destructor on the object it points to, and then *release* the memory which the program was holding in the form of allocated memory. If the memory pointed to was a block of memory locations (like an array), all elements after the 0th element will remain unchanged. Why? This is because, the pointer to an array only points to the first element (0th element), and when you delete the memory, the 0th element is uninitialized which changes its value to gibberish (similar to calling destructor on a normal object). *All other elements are left unchanged*, even though the memory now no longer belongs to the program. That is why, when you access p[4], that is, 4 memory addresses past `p`, you got the value you set earlier because it was never changed. Try accessing p[0]. It won't be the same as earlier. Also, even though p[4] works, never do this. Never access memory which does not belong to the program.
19th Feb 2021, 3:11 AM
XXX
XXX - avatar
+ 4
The delete statement release ownership of memory block <p> and <l>. Once this is done, there is no guarantee on the data that was stored on the deleted memory block. Any other program, can access the released memory block again, write and read from it again. To verify this, print *l after it is deleted, also call display(p). You will see that some (or maybe all) of the values stored on <p> and <l> may have been changed.
19th Feb 2021, 3:15 AM
Ipang