c++stringreadprocessmemory

How to use WriteProcessMemory (WPM) to replace strings?


I am trying to write a simple code to replace a string in a program by another using WPM and I am able to make it work, but only partly. This is part of the code I used to get the result.

string strWrite;
cin >> strWrite;
strWrite = strWrite + "\0";
if (WriteProcessMemory(hProcess, (LPVOID) reqdAddr, &strWrite[0], strWrite.size(), NULL) == false)
    {
        cout << "WriteProcessMemory failed. GetLastError = " << dec << GetLastError() << endl;
        system("pause");
        return EXIT_FAILURE;
    }

When I try to replace the original string DefaultString with blabla, the result I get is blablatString. I have tried things like replacing strWrite.size() by strWrite.size() + 1 and realized that the result changes to blabla String. I need help replacing the entire string and not just the part of it.


Solution

  • If (as appears to be the case) the target string is stored as a std::string then this approach is not going to work. These have an internal structure that programmers are not supposed to be privy to (unless you go digging around in the header file) and the code you have there is not taking account of that. And even if you do, the next version of the compiler is probably going to break your code.

    So consider instead (if you can) storing the target string as a simple C string. Overwriting it is then straightforward just so long as you don't run off the end and you add a terminating nul. I would do this explicitly - don't assume that the source string is nul-terminated, it may not be. Or use std::string.c_str() and copy size() + 1 bytes from that.