Let's say I have the following structures:
struct StructA { int some_member; double some_other_member; }; struct StructB { char a_char; char another_char; };
Now say that I have a buffer in memory containing a bunch of these structures, and I would like to analyze it. Each structure in the buffer is preceded by an int describing the type of structure. Like this:
struct Descriptor { int type; union { struct StructA a; struct StructB b; } data; };
What I would like to do is to point the pointer to the buffer ( char * ) to struct Descriptor * , read the type, then access the correct member of the union, and then move the pointer to the size of the member type + size of the correct member of the union (e.g. sizeof(int) + sizeof(struct StructA) ).
However, will it be a valid C code? (In the sense that this does not cause undefined behavior.) My main problem is that the memory buffer may be smaller than sizeof(struct Descriptor) , since it contains only StructB and a field of the previous type.
Is it legal to use a pointer to a structure when the underlying memory is insufficient to store the entire structure, although I only have access to the real part of the memory? Edit: if this is not valid for a structure, is it legal for a union?
If not, is there a better way? I found this comment and the answer to which it is made, but it deals with an array of the full size of the structure.
source share