调用delete []之后,仍可以访问C ++指针数组 [英] C++ pointer array is still accessible after delete[] is called

查看:96
本文介绍了调用delete []之后,仍可以访问C ++指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,调用一次delete[]释放new分配的内存.但是,在调用delete[]之后,仍然可以访问数组元素.我两次调用delete[]来确认我遇到了double free or corruption错误,这意味着内存已释放.如果释放了内存,我如何访问数组元素?如果我将类似密码的内容读入堆中,这是否可能是一个可以利用的安全性问题?

In the following code, delete[] is called once to free up the memory allocated by new. However, the array elements is still accessible after delete[] is called. I called delete[] twice to confirm that I am getting a double free or corruption error, which I am getting, which means the memory is freed. If the memory is freed, how am I able to access the array elements? Could this be a security issue which might be exploited, if I am reading something like a password into the heap?

int *foo;
foo = new int[100];

for (int i = 0; i < 100; ++i) {
    foo[i] = i+1;
}

cout << foo[90] << endl;
delete[] foo;
cout << foo[90] << endl;

给出以下输出

91 91

91 91

int *foo;
foo = new int[100];

for (int i = 0; i < 100; ++i) {
    foo[i] = i+1;
}

cout << foo[90] << endl;
delete[] foo;
delete[] foo;
cout << foo[90] << endl;

给予

*** Error in ./a.out':两次释放或损坏(顶部):0x000000000168d010 ***`

*** Error in./a.out': double free or corruption (top): 0x000000000168d010 ***`

推荐答案

内存是空闲的,这意味着它不再属于属性,但是每次删除某些内容时,编译器都不会花费额外的精力将其擦除为0.

The memory is free, which means it isn't attributed anymore, but the compiler's not going to take the extra effort to wipe it back to 0 everytime something's deleted.

在访问内存之前,也不会花费精力检查内存是否已正确分配-这会降低性能,并假定您没有这样做. (尽管诸如valgrind或调试器之类的工具可以检测到那些错误的调用)

It's also not going to take the effort to check that the memory is properly allocated before you access it - it'd reduce performance, and it assumes you don't do so. (Although tools like valgrind or debuggers can detect those wrong calls)

因此它只是在内部将内存范围更改为未分配",这意味着对new的另一个调用可以使用相同的内存范围.然后,该内存中的所有数据都将被覆盖,并且foo[90]将不再返回相同的内容.

So it just changes the range of the memory as 'unassigned' internally, which means another call to new can use that same memory range. Then whatever data in that memory would be overwritten, and foo[90] won't return the same thing anymore.

这篇关于调用delete []之后,仍可以访问C ++指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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