This is wrong for a few reasons:
Code:
for (i = 0; i < 4; i++)
{
sprintf(&data[i], "0x%c%c", *hexdata,*(hexdata + 1));
}
- you copy 4 bytes "0" "x" "%c" and "%c" starting at data[i].
- then you advance one byte and copy four more bytes, three of which are exactly the same
- "data" itself does not appear to have any allocated memory, so there is an overflow on the very first sprintf write
The last point is where we should start.
Code:
unsigned char * data;
"data" is thus an unsigned char pointer, with no memory allocated to it. It is fine to do this
data will now point to hexdata, which is a string literal. However, that means that you cannot make any changes to either one. It would be possible if hexdata was declared this way instead:
Code:
char hexdata[] = "4042a55e";
But in any case, assigning data to hexdata IS NOT the same thing as copying the contents of hexdata to data. That would look something like this:
Code:
data = malloc(strlen(hexdata)+1);
strcpy(data, hexdata);
Notice memory is allocated to data first.
As for what you are trying to do in the for() loop, you probably mean something like this:
Code:
int len = strlen(hexdata);
for (i=0;i<len;i++) {
data[i] = hexdata[i];
}
Finally, you should be aware that doing this:
Code:
char * hexdata = "4042a55e"
Does not create a 4-byte string with values 0x40, 0x42, 0xa5, 0x5e! It creates an eight byte string, one for each character. The values for each byte are the ASCII values for the character -- eg. "404" is 0x34, 0x30, 0x34.