The structure data is stored in Flash, and the analysis of the problem of element position offset

Background of the problem : Today, I debugged the Flash storage, where the stored data is a structure variable, and found that some elements in the structure variable are offset backward!
Specific reason : For example, the following structure variable test is stored in flash, and it occupies 6 bytes instead of 5 bytes; the reason is that the structure has the concept of byte alignment, that is, in the structure member The number of bytes occupied by the data type that occupies the most memory is the standard, and all members must be aligned with this length when allocating memory. Take the following structure variable test as an example. In its elements, a and c are two bytes. If b should be aligned with it, a null byte will be automatically added;

typedef struct{
	uint16_t a;
	uint8_t  b;
	uint16_t c;
}TEST_T;
TEST_T test ;

No matter how complex the structure is, the byte alignment will not be discussed. There are many examples. This record describes this basic common sense, which may lead to inconsistent effects with the previous thoughts;

Solution : If you want to avoid the waste of Flash space, you only need to add the __attribute__ feature when defining the structure variable; for example, the following

typedef struct{
	uint16_t a;
	uint8_t  b;
	uint16_t c;
}__attribute__ ((__packed__))TEST_T;
TEST_T test ;

Guess you like

Origin blog.csdn.net/weixin_43704402/article/details/113847071