user1594121
user1594121

Reputation: 117

Why is bool/char allocation 4 bytes instead of 1?

I'm trying to load a struct properly which has 1 char as a bool. It looks like it should work fine but when I printf the data at the bool it fails because it reads 4 bytes instead of 1.

typedef struct
{
    char magic[8];
    u32 version;
    bool updatable;
    u64 filetime;
    u32 region;
    u32 numentries;
    u32 fs1;
    u32 fs2;
    u8 *zonedata;
} fastfile;

int main(int argc, char **args)
{
    if(!args[1])
        return -1;
    u64 file_size;
    get_file_size(args[1], &file_size);
    u8* file_data = new u8[file_size];
    read_file(args[1], file_data, file_size); //ignore this just reading data

    fastfile* ff = (fastfile *)(file_data + 0); //this is where I setup my struct according to file data
}

There is my structure, here is what happens when I debug:

http://puu.sh/3e091/1ab766dfc6.png

Hex View:

Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00E7C910  49 57 66 66 75 31 30 30 00 00 01 0D 01 01 CA CC  IWffu100......ÊÌ
00E7C920  3F 53 50 A3 40 00 00 00 02 00 00 00 00 00 03 5B  ?SP£@..........[
00E7C930  78 DA EC 5D 09 7C 13 C5 FE DF A6 94 9B 02 0A 72  xÚì].|.Åþߦ”›..r

as you can see the pointer to the filetime is at 0xE7C920 instead of at 0xE7C91D

any ideas how I can get it to work the way I want it too? or will it not work that way because of pointers being 4 bytes long?

Upvotes: 3

Views: 716

Answers (1)

Jens
Jens

Reputation: 72786

Because of padding. Most types on modern C implementations are aligned to an address which is a multiple of their size. So in a structure, when you have a char followed by an uint64_t, there can be up to 7 padding bytes between the two. In your case, the u32 and bool take up 5 byte, so only three bytes are required to 8-align the u64.

To portably detect whether there is padding, you can use the offsetof macro from <stddef.h>.

Upvotes: 6

Related Questions