Values of padding bytes in C

0

I've spotted a strange behavior in this small C program. I have 2 structures, both with padding bytes, but in different places.

The first structure has padding bytes with indices [1:3], and the output is expected: static variables are zeroed-out, so padding values are all 0, local variables on stack are left with garbage values in padding bytes. Example output:

Char is first, then int:
aa 60 8e ef ff ff ff ff 
aa 00 00 00 ff ff ff ff 

But in the second structure, something strange happens. Padding bytes in this structure are with indices [5:7], so I expected some garbage values in non-static variable, but every time the output is:

Int is first, then char:
ff ff ff ff aa 7f 00 00 
ff ff ff ff aa 00 00 00 

Why the padding is always 7f 00 00?

The complete program:

#include "stdio.h"
#include "stdint.h"
#include "stddef.h"

//  0 1 2 3 4 5 6 7
// |a|#|#|#|b|b|b|b|
typedef struct
{
    uint8_t a;
    uint32_t b;
} S1;

//  0 1 2 3 4 5 6 7
// |a|a|a|a|b|#|#|#|
typedef struct
{
    uint32_t a;
    uint8_t b;
} S2;

void print_bytes(void* mem, size_t num_bytes)
{
    for (size_t i = 0; i < num_bytes; i++)
        printf("%02x ", *((unsigned char*)mem + i));
    putc('\n', stdout);
}

int main()
{    
    S1 var1          = { .a = 0xAA, .b = 0xFFFFFFFF };
    static S1 var1_s = { .a = 0xAA, .b = 0xFFFFFFFF };

    printf("Char is first, then int:\n");
    print_bytes(&var1,   sizeof(S1));
    print_bytes(&var1_s, sizeof(S1));

    S2 var2          = { .a = 0xFFFFFFFF, .b = 0xAA };
    static S2 var2_s = { .a = 0xFFFFFFFF, .b = 0xAA };
    
    printf("\nInt is first, then char:\n");
    print_bytes(&var2,   sizeof(S2));
    print_bytes(&var2_s, sizeof(S2));
}
c++
c
byte
padding
asked on Stack Overflow Apr 10, 2021 by Winter091

1 Answer

-2

There's no problem if I run your program. Last bytes are random. It likely depends on your system.

answered on Stack Overflow Apr 10, 2021 by thermo911

User contributions licensed under CC BY-SA 3.0