c++pointers

Can memory still be accessed after using delete[]?


If I have a pointer ptr1 which points to a dynamic array created by new[]. If I delete that pointer using delete ptr1 instead of delete[] ptr1, will the array be correctly deleted?

And, if I have another pointer ptr2 having the same value as ptr1, after using delete[] ptr1, can I still access the same array using ptr2?

For me, when I try to output the array using ptr2 after using delete[] ptr1, it displays garbage values instead of the values of the array.


Solution

  • If I have a pointer ptr1 used to create a dynamic array

    A pointer does not create an array, it merely points at a memory location, nothing more. But a pointer can point at a memory block that is holding the content of an array, yes.

    [If] I delete that pointer before deleting the array itself i.e use delete ptr1 instead of delete[] ptr1, will the array automatically be deleted?

    Not correctly, no. If you allocate the array with new[] and then try to free it with delete instead of delete[], that is undefined behavior. You must match new with delete, and new[] with delete[].

    And, if I have another pointer ptr2 having the same value as ptr1, after deleting ptr1, can I still access the array that ptr1 pointed to using ptr2?

    No. The memory block that both pointers are pointing at is no longer valid once delete/[] touches it. You cannot use either pointer anymore, unless you first reassign them to point at valid memory, or set them to nullptr.

    For me, when I try to output the array using ptr2 after deleting ptr1, it displays garbage values instead of the values of the array.

    Correct, because you are trying to access invalid memory.