Damian Andrysiak
Damian Andrysiak

Reputation: 75

C++ memory in dynamic array after delete

enter image description here. Following photo describes memory before delete and after delete. I am wondering why I still see some kind of memory address. My question is: Is it caused by compilator or I did something wrong during freeing the memory.

Code snippet:

__int16** Matrix{};
size_t width{ 35 };
size_t height{ 4 };
Matrix = new __int16* [height];
for (size_t i = 0; i < height; ++i)
{
    Matrix[i] = new __int16[width];
    for (size_t j = 0; j < width; ++j)
    {
        Matrix[i][j] = NULL;
    }
};
//DEALLOCATE ALLOCATED MEMORY
for (size_t i = 0; i < height; ++i)
{
    delete[] Matrix[i];
}
delete[] Matrix;

Upvotes: 0

Views: 149

Answers (1)

walnut
walnut

Reputation: 22162

Deallocating memory that a pointer points to does neither cause the pointer to be set to null, nor does it cause the memory that is deallocated to be zeroed.

Deallocation only means that you tell the (system) allocator that you don't use that memory anymore and that it can use it for other allocation requests. The allocator does not need to modify the memory in any way.

Dereferencing a pointer that points to memory which you deallocated by a call to delete[] causes undefined behavior. This does not mean that you will observe any particular behavior, it means that anything could happen. It could e.g. happen that the delete has no effect on your program's memory, but that still doesn't allow you to keep using it.

Upvotes: 3

Related Questions