“删除[]指针"不删除所有内存阵列? [英] "delete [] pointer" does not delete all the memory array?

查看:89
本文介绍了“删除[]指针"不删除所有内存阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++很陌生.完成循环后,我必须删除指针和内存分配.我正在使用new()进行内存分配,最后使用delete释放数据.

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.

程序如下:

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.

调用delete[]时会发生两件事:

  1. 如果数组的类型具有非平凡的析构函数,则将以相反的顺序为数组中的每个元素调用析构函数
  2. 数组占用的内存被释放

在调用delete之后访问数组占用的内存会导致未定义的行为(也就是说,任何事情都可能发生-数据可能仍然存在,或者当您尝试读取数据时程序可能崩溃,或者发生其他情况)可能会更糟).

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).

使用 RAII .要么将其包装在一个类中,要么使用STL而不自己管理内存. C ++功能强大,但是您也可以放开脚-可以这么说.更好的做法是将其置于自己的范围内,以防止超出范围的任何内容都无法访问您的指针.

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

这篇关于“删除[]指针"不删除所有内存阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆