Created
January 12, 2022 03:34
-
-
Save rossy/1938af2d795fb6f0066503633e4aa4ff to your computer and use it in GitHub Desktop.
Demonstration of how struct padding byte values are unspecified (YMMV depending on compiler)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// clang -Wall -O0 hole-struct.c -o hole-struct | |
// gcc -Wall -O0 hole-struct.c -o hole-struct | |
#include <stdio.h> | |
#include <string.h> | |
struct hole_struct { | |
char a; | |
// char hole1[3]; | |
int b; | |
char c; | |
// char hole2[3]; | |
int d; | |
}; | |
static __attribute__((noinline)) void print_bytes(const void *bytes, size_t len) | |
{ | |
const unsigned char *c = bytes; | |
while (len--) | |
printf("%02x%s", *c++, len ? " " : ""); | |
printf("\n"); | |
} | |
static __attribute__((noinline)) void fill_stack(int c) | |
{ | |
char memory[100]; | |
memset(memory, c, sizeof memory); | |
__asm__ __volatile__ ("" ::: "memory"); | |
} | |
static __attribute__((noinline)) void init_struct(int a, int b, int c, int d) | |
{ | |
struct hole_struct s = { .a = a, .b = b, .c = c, .d = d }; | |
print_bytes(&s, sizeof s); | |
} | |
int main() | |
{ | |
fill_stack(0x55); | |
init_struct(1, 2, 3, 4); // 01 55 55 55 02 00 00 00 03 55 55 55 04 00 00 00 | |
fill_stack(0xaa); | |
init_struct(1, 2, 3, 4); // 01 aa aa aa 02 00 00 00 03 aa aa aa 04 00 00 00 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment