c++ - Cannot properly memcpy a char array to struct -
so have construct called packet
struct packet { unsigned int packet_type; wchar_t packet_length[128]; wchar_t file_name[256]; wchar_t template_name[256]; wchar_t file_name_list[1024]; wchar_t file_data[1024]; void serialize(char * dat) { memcpy(dat, this, sizeof(packet)); } void deserialize(const char * dat) { memcpy(this, dat, sizeof(packet)); } };
i'm trying desieralize data
{byte[2692]} [0] 0 unsigned int packet_type; (4 bytes) [1] 0 [2] 0 [3] 0 [4] 50 '2' wchar_t packet_length[128]; (128 bytes) [3] 0 [5] 54 '6' [3] 0 [6] 57 '9' [3] 0 [7] 50 '2' [8] 0 [...] 0 [132] 112 'p' wchar_t file_name[256]; (256 bytes) [133] 0 [134] 104 'h' [...] 0
but memcpy in deserialze isn't giving me file_name, give me packet_length. what's this? thanks!
edit: it's clear me wchar_t taking more space once thought; however, i'm being told not use memcpy @ all?
i've written deserialize method , grabs data correctly. still cause security leak?
void deserialize(const char * dat) { memcpy(&(packet_type), dat, 4); memcpy(&(packet_length[0]), dat + 4, 128); memcpy(&(file_name[0]), dat + 132, 256); memcpy(&(template_name[0]), dat + 388, 256); memcpy(&(file_name_list[0]), dat + 644, 1024); memcpy(&(file_data[0]), dat + 1668, 1024); }
the layout of char
array assumes size of wchar_t
2 bytes; not - here example of system size of wchar_t
4
, size of packet
10756
, not 2692
bytes: (link demo).
that why memcpy
trick edit presents problem: assumes layout of data in char[]
array matches layout of wchar_t[]
arrays, may or may not match. if know data array has two-character elements stored in little endian format (lsb first), can write own function converts data source destination, , call portions of serialized data, this:
void bytes_to_wchar(wchar_t *dest, const unsigned char* src, size_t length) { (size_t = 0 ; != lengt ; i++) { dest[i] = src[2*i] | (src[2*i+1] << 8); } }
now can use function copy data wchar_t
arrays independently of wchar_t
size on target system, or endianness of target system:
void deserialize(const char * dat) { bytes_to_wchar(packet_type, dat + 0, 4); bytes_to_wchar(packet_length[0], dat + 4, 128); bytes_to_wchar(file_name[0], dat + 132, 256); bytes_to_wchar(template_name[0], dat + 388, 256); bytes_to_wchar(file_name_list[0], dat + 644, 1024); bytes_to_wchar(file_data[0], dat + 1668, 1024); }
the shortcut of saving data memory , writing may work when on same hardware, using same compiler. remains sensitive small adjustments in headers use , in settings of compiler.
if character array need copy struct
has fixed layout, need write function process layout, converting two-byte groups wchar_t
s, four-byte groups unsigned int
s, , on.
Comments
Post a Comment