Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Fix:

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

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

You have the parameter

char** buf

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top