Packed structure reading from EFS giving strange result

90 views Asked by At

I have created one EFS item, that has the following structure

struct 
{
    uint8 version;   // uint8 - 1 byte data type, uint16 - 2 byte
    uint16 y1;
    uint16 y2;
    uint16 y3;
    uint8 reserved[9];
}

Now the EFS file size comes out to be 16 byte, so I think it is packed.

Now I have same structure, on which on power up I read the values from EFS, But the Size of the structure returned by my compiler comes out to be 18 byte( Compiler doesn't support Packing, so EFS reading was failing).

I read only 16 byte and It passed.

Questions:

(1). If I read only 16 byte, isn't there a risk of data loss, as After the first member there will be one byte padded space in my structure( as my compiler doesn't support Packed structure and I cannot use it) I wrote the following values to the EFS,

version -0
y1      -6
y2      -10
y3      -60

I read only 16 byte, and every member of my structure was assigned correct values. is there any scenario where my structure will have wrong values.

(2). Due to confusion at step one, i created one temporary struture like below

struct
{ 
    uint8 version;
    uint8 y1_a;
    uint8 y1_b;
    uint8 y2_a;
    uint8 y2_b;
    uint8 y3_a;
    uint8 y3_b;
    uint8 reserved[9];
}

Now both the EFS and structure size is 16 byte, Now when I give the input to EFS as version =0, y1=6, y2=10, y3=60,

The members are assigned values like this :version=0,y1_a = 6, y1_b =0, y2_a = 10, y2_b =0, y3_a =60, y3_b =0;

can someone help in understanding this? My idea is to read in temp structure( so that both the size of EFs and my structre comes out to be same) and then assign values to my original struture from temp struture

1

There are 1 answers

1
Martin Rosenau On

I assume that you read the data just by copying the bytes from the EFS to the structure.

(If you fill your structure like this:

read(&(s.version)...);
read(&(s.y1)...);

you do not have any problems with packed or unpacked structures, of course... However you would have to ensure that writing is done in the same way.)

Depending on the compiler the data read by the EFS will definitely not be assigned correctly.

To check how packing is done by the compiler I would do two tests:

int a = ((int)&(s.y1)) - ((int)&(s.version));

This will be 1 if the compiler does packing, 2 if not.

union {
    struct {
        uint8 version;
        uint16 y1;
        ...
    } unsure;
    struct {
        uint8 version;
        uint8 y1_a;
        uint8 y1_b;
        ...
    } definitely_unpacked;
}

This union should give you a more detailed idea on what is going on: When reading the data into the union you can see which uint8 in the second struct will map to which uint16 in the first one.