I have a unsigned char pointer which contains a structure.Now I want to do the following
unsigned char buffer;
//code to fill the buffer with the relevant information.
int len = ntohs((record_t*)buffer->len);
error: request for member ‘len’ in something not a structure or union.
int len = ntohs(((record_t*)buffer)->len);
dereferencing type-punned pointer will break strict-aliasing rules
record_t *rec = null;
rec = (record_t*)
According to the C and C++ standards, it is undefined behaviour to access a variable of a given type through a pointer to another type. Example:
int a; float * p = (float*)&a; // #1 float b = *p; // #2
Here #2 causes undefined behaviour. The assignment at #1 is called "type punning". The term "aliasing" refers to the idea that several different pointer variables may be pointing at the same data -- in this case,
p aliases the data
a. Legal aliasing is a problem for optimization (which is one of the main reasons for Fortran's superior performance in certain situations), but what we have here is flat-out illegal aliasing.
Your situation is no different; you're accessing data at
buffer through a pointer to a different type (i.e. a pointer that isn't
char *). This is simply not allowed.
The upshot is: You should never have had data at
buffer in the first place.
But how to solve it? Make sure you have a valid pointer! There is one exception to type punning, namely accessing data through a pointer to char, which is allowed. So we can write this:
record_t data; record_t * p = &data; // good pointer char * buffer = (char*)&data; // this is allowed! return p->len; // access through correct pointer!
The crucial difference is that we store the real data in a variable of the correct type, and only after having allocated that variable do we treat the variable as an array of chars (which is allowed). The moral here is that the character array always comes second, and the real data type comes first.