我很困惑,我认为我的调试器对我说谎.我的代码中有以下循环:
MyClass::UploadFile(CString strFile)
{
...
static DWORD dwLockWaitTime = EngKey::GetDWORD(DNENG_SERVER_UPLOAD_LOCK_WAIT_TIME, DNENG_SERVER_UPLOAD_LOCK_WAIT_TIME_DEFAULT);
static DWORD dwLockPollInterval = EngKey::GetDWORD(DNENG_SERVER_UPLOAD_LOCK_POLL_INTERVAL, DNENG_SERVER_UPLOAD_LOCK_POLL_INTERVAL_DEFAULT);
LONGLONG llReturnedOffset(0LL);
BOOL bLocked(FALSE);
for (DWORD sanity = 0; (sanity == 0 || status == RESUMABLE_FILE_LOCKED) && sanity < (dwLockWaitTime / dwLockPollInterval); sanity++)
{
...
Run Code Online (Sandbox Code Playgroud)
在我的程序过程中,这个循环已被执行了数百次,并且两个静态变量在代码中的任何地方都没有改变,当它们被静态初始化并在循环条件下读取时,它们只被写入一次其他地方.由于它们是从Windows注册表中读取的用户设置,因此它们几乎总是具有dwLockWaitTime = 60和dwLockPollInterval = 5的常量值.因此循环始终为60/5.
很少,我得到一个崩溃转储,显示这行代码已经抛出除零错误.我已经检查了WinDbg所说的内容,它显示:
FAULTING_IP:
procname!CServerAgent::ResumableUpload+54a [serveragent.cpp @ 725]
00000001`3f72d74a f73570151c00 div eax,dword ptr [proc!dwLockPollInterval (00000001`3f8eecc0)]
EXCEPTION_RECORD: ffffffffffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 000000013f72d74a (proc!CServerAgent::ResumableUpload+0x000000000000054a)
ExceptionCode: c0000094 (Integer divide-by-zero)
ExceptionFlags: 00000000
NumberParameters: 0
ERROR_CODE: (NTSTATUS) 0xc0000094 - …Run Code Online (Sandbox Code Playgroud) void func(){
int *ptr;
printf("\n *** %d\n",*ptr);
ptr=malloc(sizeof(int));
*ptr=111;
printf("\n ##### %d\n",*ptr);
}
int main()
{
func();
func();
return(0);
}
Run Code Online (Sandbox Code Playgroud)
GCC输出
*** -1991643855 // Junk value for the first call
##### 111 // After allocating and assigning value
*** 111 // second call pointer the value which 111
##### 111 // second call after assigning
Run Code Online (Sandbox Code Playgroud)
我对func()中malloc的行为感到困惑.在第一次调用之后,局部变量指针ptr在堆栈帧中被清除.在第二次调用期间,将在新的堆栈帧中再次创建ptr.所以ptr并没有指向任何地方.那么为什么在第二次调用中打印时,它指向111的内存位置.这可能非常愚蠢.我经常搜索Google,但没有找到明确的答案.
我试图更好地理解 unordered_set 。主要是,据我了解,unordered_set 中的元素在 equal_to 运算符之前应该是唯一的。因此,我决定通过一小段代码来测试一下
#include <iostream>
#include <unordered_set>
using namespace std;
struct m_int
{
int x;
};
// template specialization for std::hash
template<>
struct std::hash<m_int>
{
std::size_t operator()(m_int const& x) const noexcept
{
return hash<int>{}(x.x);
}
};
//template specialization for std::equal_to
template<>
struct std::equal_to<m_int>
{
bool operator()(const m_int &lhs, const m_int &rhs) const
{
return abs(lhs.x-rhs.x)<=3;
}
};
int main() {
unordered_set<m_int> m={{1},{2},{3},{4}};
for(auto&x:m)
cout<<x.x<<' ';
cout<<endl;
cout<<m.count({2})<<endl;
// your code goes here
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我最初的想法是1会插入2,3会但会插入4。
我得到的输出是 …