简体   繁体   中英

C++ memcpy not copying as expected

    BYTE* uMemory;
    std::string data = "00 00 00 2D 01 00 B0 F9 1E 00"
    data.erase(remove_if(data.begin(), data.end(), isspace), data.end());

    int address = 0;
    for (int i = 0; i < data.length(); i += 2)
    {
        std::string data_1 = data.substr(i, 2);
        int num2 = std::stoi(data_1, 0, 16);
        memcpy(&uMemory + address, &num2, 2);
        address++;
    }

I'm trying to copy this into memory (2E 01 00 00 00 2D 01 00 B0 F9 1E 00) for uMemory but I don't understand the logic of it.

No matter the amount of bytes I want it to copy it always ends up like this in memory:

00 00 00 00 00 00 00 00 00 01 00 00 2D 00 00 00 01 00 00 00 00 00 00 00 B0 00 00 00 F9 00 00 00 1E 00 00 00

Your immediate problem here is that uMemory is a pointer, and in the line

memcpy(&uMemory + address, &num2, 2);

you are forming a pointer to a pointer . &uMemory has type BYTE** , so when you do pointer arithmetic you're moving over one pointer-width each time, which is apparently 4 bytes on your platform judging by your output.

You're also clobbering a random section of memory of when you write here, likely the memory holding the data object itself (since that's what's declared immediately after the pointer.)

This was my solution. I would love some alternatives for better coding practices if possible.

    std::atomic<BYTE> uMemory[256];
    int address = 0;
    std::vector<BYTE> array;
    for (int i = 0; i < data.length(); i += 2)
    {
        std::string data_1 = data.substr(i, 2);
        DWORD num2 = std::stoi(data_1, 0, 16);
        array.push_back(num2);
    }

    std::copy(std::begin(array), std::end(array), std::begin(uMemory));

The only thing I'm not understanding is that I have to have std::atomic in order for the memory to not become random. Is there a different way of doing this?

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