C++ got pointer instead of value -


i wondering why pointer value (324502) in var signallengthdebugvar1 instead of expected integer value (2)?

struct shmlengthofsignalname {     int signallength; }; //... byte*   pbuf        = null; //... int main(void){      //...     pbuf = (byte*) mapviewoffile(hmapfile, file_map_all_access, 0, 0, buf_size);     //...     jobasignal sig1;     printf("value signallength: %d \r\n", pbuf[30]); // 2     const shmlengthofsignalname * signalnamelengthptr = (const shmlengthofsignalname *)(pbuf + 30);      int signallengthdebugvar1 = signalnamelengthptr->signallength; // content: 324502 maybe pointer?     int signallengthdebugvar2 = (int) pbuf[30]; // content 2     sig1.setnamelength(signallengthdebugvar2);  } 

when print value, you're reading single byte @ pbuf + 30:

// takes pbuf[30], converts byte's value int, , prints printf("value signallength: %d \r\n", pbuf[30]); // 2 

later, when cast pointer , dereference it, you're accessing a full int, sizeof(int) bytes (likely 4). occupies not byte @ pbuf + 30 subsequent bytes @ pbuf + 31, etc., sizeof(int) on platform. interprets these bytes according platform's byte-endianness (little-endian intel, big-endian other platforms).

// signallength struct member int int signallengthdebugvar1 = signalnamelengthptr->signallength; // content: 324502 maybe pointer? 

note compiler permitted add padding before or after loation of signallength field. in other words, can't assume signallength start @ struct offset zero, unless use extern "c" or compiler-specific #pragma. , then, can't control endianness interpretation, if data encoded big-endian , you're on little-endian machine x86, value see wrong.

the bottom line in c++ not safe way decode binary data.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -