Riddle Wrong
Riddle Wrong

Reputation: 55

Writing DWORD to memory overwrites only 1 byte instead of 4

I have

typedef unsigned int DWORD;

void write_str(string str, char** buf) {
    DWORD len = str.size();
    **buf = len;
    *buf += sizeof(len);
    memcpy(*buf, str.c_str(), len);
    *buf += len;
}

This code, and only 1 byte is overwriten in **buf = len; if i have i.e. 7 in len while 4 should be, since sizeof(DWORD) = 4

Upvotes: 0

Views: 638

Answers (4)

Jurlie
Jurlie

Reputation: 1014

1 byte is overwritten since the destination type is char (the type of **buf is char). This is correct. But the expression *buf += sizeof(len) has no meaning in my opinion.

Upvotes: 0

Drew
Drew

Reputation: 101

Fix:

DWORD *tmpptr(*buf);
*tmpptr = len;

C++ is automatically casting len to a char, since that is what *buf is.

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92381

You have the parameter

char** buf

Meaning that **buf is a char, which is very likely a single byte.

Upvotes: 0

Didier Trosset
Didier Trosset

Reputation: 37487

As buf is a char **, **buf is a char. It can hold only a single byte. Therefore, only a single byte is written to it.

Upvotes: 1

Related Questions