Skip to content

Instantly share code, notes, and snippets.

@latsku
Last active August 29, 2015 14:20
Show Gist options
  • Save latsku/bbe9d4d93ca0822fbe6b to your computer and use it in GitHub Desktop.
Save latsku/bbe9d4d93ca0822fbe6b to your computer and use it in GitHub Desktop.
Test file to demonstrate structure packing on C
/**
* \file
* Test to show how packed structures work in C.
*
* Eric S. Raymond has written a great introduction to structure packing
* (http://www.catb.org/esr/structure-packing/)
*
* @author: Lari Lehtomäki <lari@lehtomaki.fi>
* @date: 2015-05-29
*
*/
#include <stdio.h>
/**
* Test structure
* Try with and without the packed attribute.
*/
struct myStruct {
//struct __attribute__ ((__packed__)) myStruct {
short unsigned int a;
unsigned int b;
short unsigned int c;
};
/** Buffer where the structs points. */
static char buffer[20];
/**
* On little-endian machine (x86) the output with packed structure
* should be something like:
* \code
*
* sym: 8
* sym.a: 2
* sym.k: 4
* sym.m: 2
* *si = (myStruct) {
* .a = 0x0123,
* .b = 0x456789ab,
* .c = 0xcdef
* };
* 0x601041: 0x23 0x01 0xab 0x89 0x67 0x45 0xef 0xcd
*
* \endcode
*/
int main(int argc, const char *argv) {
struct myStruct *si = (struct myStruct *)buffer;
*si = (struct myStruct) {
.a = 0x0123,
.b = 0x456789ab,
.c = 0xcdef
};
printf("sym: %lu\n", sizeof(*si));
printf("sym.a: %lu\n", sizeof(si->a));
printf("sym.k: %lu\n", sizeof(si->b));
printf("sym.m: %lu\n", sizeof(si->c));
/* Printing of struct */
printf(" *si = (struct myStruct) {\n");
printf(" .a = %#06x,\n", si->a);
printf(" .b = %#06x,\n", si->b);
printf(" .c = %#06x \n", si->c);
printf(" };\n");
/* Printing of memory */
void * p = &si;
int i = 0;
printf("%p: ", &(buffer[i])+1);
for (i = 0; i < sizeof(*si); i++ ) {
printf("%#04hhx ", (char)buffer[i]);
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment