我发现了相似的SO问题,但与我的不同位置。
我的函数看起来像这样:
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;
}
系统抛出运行时异常,并说“运行时检查失败2-变量'sourceCount'周围的堆栈已损坏”。
但是,如果将sourceCount和destCount转换为变量,则不会收到此错误:
BOOL ShallowCopy(const LPVOID psource, LPVOID pdest) {
LPBYTE ps = reinterpret_cast<LPBYTE>(psource);
LPBYTE pd = reinterpret_cast<LPBYTE>(pdest);
LPBYTE pbCount = new BYTE[8];
ULONG sourceCount = 0, destCount = 0;
std::copy(ps, ps + 8, checked_array_iterator<LPBYTE>(pbCount, 8)); // Get psource byte count
sourceCount = *((PULONG)pbCount);
std::copy(pd, pd + 8, checked_array_iterator<LPBYTE>(pbCount, 8)); // Get pdest byte count
destCount = *((PULONG)pbCount);
delete[] pbCount;
if (sourceCount != destCount) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::copy(ps, ps + sourceCount, checked_array_iterator<unsigned char *>(pd, destCount));
return TRUE;
}
当我看这2个函数时,没有什么区别,只是稍后将值存储到变量中,然后转换为目标。那么,究竟是什么导致运行时错误?
ULONG
被定义为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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句