Forums - sizeof(uint8) = sizeof(uint16)

1 post / 0 new
sizeof(uint8) = sizeof(uint16)
Join Date: 29 Jul 16
Posts: 25
Posted: Wed, 2016-11-23 13:24

In the gatt_client sample app, gatt_access.c file, there is this comment:

"sizeof(uint16) / sizeof(uint8) is always 2"

In fact, this is not true. My code:

        char sc; uint8 s8; uint16 s16; uint32 s32; bool sb;
        uint8 arr8[3] = {2, 3, 4}; uint16 arr16[3] = {0x1234, 0x5678, 0x9abc };
        PRINT("Sizeof char=%d, int8=%d, int16=%d, int32=%d, bool=%d, array8=%d, array16=%d\r\n",
                sizeof(sc), sizeof(s8), sizeof(s16), sizeof(s32), sizeof(sb), sizeof(arr8) , sizeof(arr16) );

gives this output:

Sizeof char=1, int8=1, int16=1, int32=2, bool=1, array8=3, array16=3

It looks like unit8, uint16, char and bool are all implemented as 16-bit values by the compiler. I am not a C specialist, but it looks like this is permitted:

It does mean that a good deal of care needs to be taken when assuming the size taken by variable and structures. Wikipedia warns "It is generally not safe to presume to know the size of any datatype"

As it happens, the code in gatt_access.c does not actually rely on the comment "sizeof(uint16) / sizeof(uint8) is always 2" being true. But users should be warned. I only found this out when exploring the contents of a structure being saved and restored by Nvm_Write() and Nvm_Read() - a string took two bytes per character.  I suspect these only work because the smallest entity stored and retrieved by the Nvm code (uint16) is also the size of the uint, char and bool variables, and would break if the compiler changed its policy.

This probably also partly explains another bug I found, consistent with uint8 being treated at 16-bit values, which I will put in a separate post.

Regards - Charles


  • Up0
  • Down0

Opinions expressed in the content posted here are the personal opinions of the original authors, and do not necessarily reflect those of Qualcomm Incorporated or its subsidiaries (“Qualcomm”). The content is provided for informational purposes only and is not meant to be an endorsement or representation by Qualcomm or any other party. This site may also provide links or references to non-Qualcomm sites and resources. Qualcomm makes no representations, warranties, or other commitments whatsoever about any non-Qualcomm sites or third-party resources that may be referenced, accessible from, or linked to this site.