gpt4 book ai didi

c++ - 运行时检查失败 #2 - 变量周围的堆栈已损坏 C++

转载 作者:行者123 更新时间:2023-11-30 02:05:15 25 4
gpt4 key购买 nike

这是我的代码:

#include <iostream>
#include <typeinfo.h>

typedef struct A
{

friend class W;

private:
char c;
void *v;
} A;

typedef struct LL
{

friend class W;

private:
int n;
LL *next, *prev;
} LL;

class W
{

private:
void Handle(void *arg1, void *arg2)
{
A *ob1 = reinterpret_cast<A*>(arg1);
ob1->c = 'c';
ob1->v = (void*)0xffffffff;

LL *ob2 = reinterpret_cast<LL*>(arg2);
ob2->n = 0xff;
ob2->next = new LL();
ob2->prev = 0;
}

protected:
void Set()
{
A *ob1 = new A();
LL *ob2 = new LL();

this->Handle(&ob1, &ob2);
}
};

class R : W
{

public:
R(void)
{
this->Set();
}
};

void main(void)
{
R *ob = new R();
}

我从转储中得到下一个结果:运行时检查失败 #2 - 变量“ob2”周围的堆栈已损坏。

“http.exe”:已加载“C:\Users\root\Documents\Visual Studio 2008\Projects\http\Debug\http.exe”
,已加载符号。
“http.exe”:已加载“C:\Windows\SysWOW64\ntdll.dll”
“http.exe”:已加载“C:\Windows\SysWOW64\kernel32.dll”
“http.exe”:已加载“C:\Windows\SysWOW64\KernelBase.dll”
'http.exe': 已加载 'C:\Windows\winsxs\x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb\msvcr90d.dll'
运行时检查失败 #2 - 变量“ob2”周围的堆栈已损坏。

我的问题是:
- 我应该怎么做才能解决这个问题?
- 为什么我有这样的错误,你能描述一下,为什么它被完全损坏了吗?
- 为什么堆栈损坏?不是堆?

谢谢,
最好的问候,

最佳答案

A *ob1 = new A();
LL *ob2 = new LL();

this->Handle(&ob1, &ob2);

ob1ob2 已经是指针。通过获取变量的地址(类型分别为 A**LL**),然后将它们传递给 HandleA*LL*reinterpret_cast 敲入,然后写入,代码调用未定义的行为。在这种特殊情况下,它似乎正在写入 ob1ob2 变量附近的位置,它们可能位于调用 Set 的堆栈帧中>.

如果代码没有使用 reinterpret_cast 来破坏类型系统,而是正确地使用它,编译器会立即捕获到错误:

void Handle(A *arg1, LL *arg2)
{
ob1->c = 'c';
ob1->v = (void*)0xffffffff;

ob2->n = 0xff;
ob2->next = new LL();
ob2->prev = 0;
}

// ...
// the compiler would complain about this call making the problem clear
this->Handle(&ob1, &ob2);

如果代码没有到处使用那么多指针会更好,但我假设这只是一段简单的代码来演示问题。

关于c++ - 运行时检查失败 #2 - 变量周围的堆栈已损坏 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com