简体   繁体   中英

Avoid a variable optimized out with multithread c++

I'm making a program in c++ and I've a Thread working with .detach(); and when I try to access another thread from it, the debugger say that the response has been optimized out and I can't access it. Is there any way to "fix" that? Thanks

Here you have the code:

int foos;
unsigned int ReadProcess(HANDLE phandle, unsigned int address) {
    unsigned int Pointer;
    ReadProcessMemory(phandle, (void*)(address), &Pointer, sizeof(address), 0);
    return Pointer;
}

void foo()
{
    while (1) {
        if (foos == 1) { break; }
        volatile unsigned int xPointer, xBaseaddress = 0x002CF7DC, xoffset = 0x448, xoffset1 = 0x198, xoffset2 = 0x498, xoffset3 = 0x268, xoffset4 = 0x24;
        HANDLE phandle = GetProcessHandle("Speed Calculator");
        DWORD Base = (DWORD)GetBaseAddress(phandle);
        xPointer = Base + xBaseaddress; //xPointer optimized out here
        xPointer = ReadProcess(phandle, xPointer) + xoffset; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset1; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset2; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset3; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset4; //and here
        if (!SendMessage(textBox1, WM_SETTEXT, NULL, (LPARAM)("IS: ") + xPointer))//and because of that, here
            MessageBox(0, "Error: " + GetLastError(), "Error", MB_OK);
        Sleep(299);
    }
}

void main() {

                foos = 0;
                std::thread first(foo);
                first.detach();

}

I've Ignored part of my code because it's mostly a win32 api interaction.

The compiler has been called with parameters requesting that the code be optimized.

Visual Studio Example

Have a look at your solution configuration in Visual Studio (the drop down where you have either Release or Debug to select).

If you change to Debug then the variables should not be optimized out and you can see what is happening.

What happens when you change the solution configuration is that Visual Studio sets the parameters for that configuration when it call the compiler. In this case we would prefer the /Od (Disabled) flag for Configuration properties→C/C++→Optimization→Optimization as opposed to /O2 (Maximize Speed) .

During debug you can also open a "Threads" window to see the threads that are created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM