取消引用已删除的指针总是会导致访问冲突?

2021-12-13 00:00:00 memory pointers visual-c++ crash c++

我这里有一个非常简单的 C++ 代码:

I have a very simple C++ code here:

char *s = new char[100];
strcpy(s, "HELLO");
delete [] s;
int n = strlen(s);

如果我通过按 F5(开始调试)从 Visual C++ 2008 运行此代码,这总是会导致崩溃(访问冲突.)但是,在 IDE 之外启动此可执行文件,或使用 IDE 的Ctrl+F5(不调试启动)不会导致任何崩溃.可能有什么不同?

If I run this code from Visual C++ 2008 by pressing F5 (Start Debugging,) this always result in crash (Access Violation.) However, starting this executable outside the IDE, or using the IDE's Ctrl+F5 (Start without Debugging) doesn't result in any crash. What could be the difference?

我也想知道是否可以稳定重现访问已删除区域导致的访问冲突崩溃?这种崩溃在现实生活中很少见吗?

I also want to know if it's possible to stably reproduce the Access Violation crash caused from accessing deleted area? Is this kind of crash rare in real-life?

推荐答案

通过删除的指针访问内存是未定义行为.您不能期望任何可靠/可重复的行为.

Accessing memory through a deleted pointer is undefined behavior. You can't expect any reliable/repeatable behavior.

很可能在一种情况下它有效",因为字符串仍然坐在那里"在现在可用的内存中 -= 但你不能依赖它.VS 使用调试值填充内存以帮助强制崩溃以帮助查找这些错误.

Most likely it "works" in the one case because the string is still "sitting there" in the now available memory -= but you cannot rely on that. VS fills memory with debug values to help force crashes to help find these errors.

相关文章