Вопрос

I'm pretty new to C++. I have to delete the pointer and memory allocation, once I complete the cycle. I am using new() for memory allocation and delete at the end to free the data.

The program is as follows:

int main()
{

    float *ptr;

    ptr = new float[16];

    for(int i=0; i<16; i++) 
    {
        ptr[i] = 10.0f+i;
        cout << i << " " << ptr[i] << endl;
    }

    delete[] ptr;

    cout << ptr[2] << endl;  **// I STILL HAVE THE VALUE AT THIS ADDRESS. AFTER DELETING**

    }

return 0;
}

Why does the data still exist in the memory even after deleting it.

Это было полезно?

Решение

This is undefined behavior. You are accessing memory after you have deleted it.

Because deleting a block of memory does not zero the value of all pointers that point to it. Deleting memory merely makes a note that the memory is available to be allocated for some other purpose. Until that happens, the memory may appear to be intact -- but you can't count on it. And on some compiler/runtime/architecture combinations, your program will behave differently.

Two things happen when delete[] is called:

  1. If the array is of a type that has a nontrivial destructor, the destructor is called for each of the elements in the array, in reverse order
  2. The memory occupied by the array is released

Accessing the memory that the array occupied after calling delete results in undefined behavior (that is, anything could happen--the data might still be there, or your program might crash when you try to read it, or something else far worse might happen).

Use RAII. Either wrap it in a class or use the STL and don't manage memory yourself. C++ is powerful, but you can also blow your leg off - so to speak. A better practice would be to put it in its own scope would prevent anything beyond the scope from accessing your pointer.

{
    Foo* pFoo = new Foo;
    // use pFoo
    delete pFoo;
}
// anything using pFoo beyond here fails at compilation
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top