调用delete []之后,仍可以访问C ++指针数组

编程入门 行业动态 更新时间:2024-10-27 10:18:12
本文介绍了调用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 ++指针数组

本文发布于:2023-10-26 21:43:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   delete

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!