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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…