Skip to content

Instantly share code, notes, and snippets.

@911992
Created June 30, 2020 15:50
Show Gist options
  • Save 911992/bcfe7dae4ad3e1d752841ccfd58f1f08 to your computer and use it in GitHub Desktop.
Save 911992/bcfe7dae4ad3e1d752841ccfd58f1f08 to your computer and use it in GitHub Desktop.
C Struct Padding Example
#include <stdio.h>
/*Author: https://github.com/911992*/
typedef struct s{
int b;
char f;
char _data[9];
};
int main(void) {
printf("sizeof(struct s) : %d\n",sizeof(struct s)); // 16
struct s _s;
memset(&_s,0,sizeof(struct s));
_s.b= 0xaaaaaaaa;
_s.f = 0xbb;
memset(_s._data,0xcc,sizeof(_s._data));
printf("_data len : %d\n",sizeof(_s._data)); // returns 9, but actually 11
printf("a:%x , f:%x\n",_s.b,_s.f&0xff); // 0xaaaaaaaa , 0xbb
printf("arr: {");
for(int a=0;a<sizeof(_s._data);a++){
printf(" %x ",_s._data[a]&0xff);
} // { cc cc cc cc cc cc cc cc cc }
printf("}\nall_struct arr: {");
char* _ptr = (char*)&_s;
for(int a=0;a<sizeof(struct s);a++){
printf(" %x ",_ptr[a]&0xff);
} // { aa aa aa aa bb cc cc cc cc cc cc cc cc cc 0 0 }
// Mind the these two zeros, as padded bytes ^^^^
printf("}\n");
//surprise here
printf("Altering padded data\n");
_s._data[9] = 0xee; // expecting error? but no, becasue of padding(at the end)
_s._data[10] = 0xdd; // expecting error? but no, becasue of padding(at the end)
printf("}\nall_struct arr(after alter): {");
for(int a=0;a<sizeof(struct s);a++){
printf(" %x ",_ptr[a]&0xff);
} //{ aa aa aa aa bb cc cc cc cc cc cc cc cc cc ee dd }
printf("}\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment