C++ C++;-运行时检查失败#2-堆栈周围变量';sourceCount';腐败
我发现类似的问题,但和我的不同 我的函数如下所示:C++ C++;-运行时检查失败#2-堆栈周围变量';sourceCount';腐败,c++,C++,我发现类似的问题,但和我的不同 我的函数如下所示: BOOL ShallowCopy(const LPVOID psource, LPVOID pdest) { LPBYTE ps = reinterpret_cast<LPBYTE>(psource); LPBYTE pd = reinterpret_cast<LPBYTE>(pdest); ULONG sourceCount = 0, destCount = 0; std::copy(
BOOL ShallowCopy(const LPVOID psource, LPVOID pdest) {
LPBYTE ps = reinterpret_cast<LPBYTE>(psource);
LPBYTE pd = reinterpret_cast<LPBYTE>(pdest);
ULONG sourceCount = 0, destCount = 0;
std::copy(ps, ps + 8, checked_array_iterator<LPBYTE>(((LPBYTE)((LPVOID)&sourceCount)), 8)); // Get psource byte count
std::copy(pd, pd + 8, checked_array_iterator<LPBYTE>(((LPBYTE)((LPVOID)&destCount)), 8)); // Get pdest byte count
if (sourceCount != destCount) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::copy(ps, ps + sourceCount, checked_array_iterator<unsigned char *>(pd, destCount));
return TRUE;
}
if (!ShallowCopy(pcsbi, &csbi)) {
cerr << _T("FATAL: Shallow copy failed.") << endl;
}
BOOL ShallowCopy(常量LPVOID psource,LPVOID pdest){
LPBYTE ps=重新解释强制转换(psource);
LPBYTE pd=重新解释强制转换(pdest);
ULONG sourceCount=0,destCount=0;
std::copy(ps,ps+8,checked_数组_迭代器(((LPBYTE)((LPVOID)和sourceCount)),8));//获取psource字节计数
std::copy(pd,pd+8,checked_数组_迭代器(((LPBYTE)((LPVOID)和destCount)),8));//获取pdest字节计数
if(sourceCount!=destCount){
SetLastError(错误\无效\参数);
返回FALSE;
}
复制(ps,ps+sourceCount,checked_数组_迭代器(pd,destCount));
返回TRUE;
}
当我这样调用函数时:
BOOL ShallowCopy(const LPVOID psource, LPVOID pdest) {
LPBYTE ps = reinterpret_cast<LPBYTE>(psource);
LPBYTE pd = reinterpret_cast<LPBYTE>(pdest);
ULONG sourceCount = 0, destCount = 0;
std::copy(ps, ps + 8, checked_array_iterator<LPBYTE>(((LPBYTE)((LPVOID)&sourceCount)), 8)); // Get psource byte count
std::copy(pd, pd + 8, checked_array_iterator<LPBYTE>(((LPBYTE)((LPVOID)&destCount)), 8)); // Get pdest byte count
if (sourceCount != destCount) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::copy(ps, ps + sourceCount, checked_array_iterator<unsigned char *>(pd, destCount));
return TRUE;
}
if (!ShallowCopy(pcsbi, &csbi)) {
cerr << _T("FATAL: Shallow copy failed.") << endl;
}
if(!ShallowCopy(pcsbi和csbi)){
cerrULONG
被定义为unsigned long
,那么它只有32位(4字节,而不是代码中的8字节)
出现该错误是因为在堆栈分配的变量destCount
(或sourceCount
,它们的位置和顺序只是一个实现细节)之后覆盖内存。在第二个示例中,它起作用是因为您分配了足够的内存(pbCount
为8字节),而这sourceCount=*((PULONG)pbCount);
将只复制其中4个
我建议使用sizeof
而不是硬编码的数据类型大小:
std::copy(ps, ps + sizeof(ULONG)...
请注意,您甚至可以简单地写下:
sourceCount = *reinterpret_cast<PULONG>(ps);
destCount = *reinterpret_cast<PULONG>(pd);
sourceCount=*重新解释强制转换(ps);
destCount=*重新解释铸造(pd);
什么是csbi
和pcsbi
?非常感谢,您的解释正是我想要的。