Skip to content

Instantly share code, notes, and snippets.

@mshafeeqkn
Last active June 15, 2024 01:06
Show Gist options
  • Save mshafeeqkn/1f00be9fb1ad0046ee4a0bfc8c0f6b3e to your computer and use it in GitHub Desktop.
Save mshafeeqkn/1f00be9fb1ad0046ee4a0bfc8c0f6b3e to your computer and use it in GitHub Desktop.
Print the dump of a structure which will be useful for understanding structure padding
void dump_structure(void *ptr, unsigned long size) {
unsigned long addr;
// Top row of the table
printf("\nSize of the structure: %lu\n ", size);
for(int i = 0; i <= 0xf; i++) {
if(i == 8) printf(" ");
printf(" %x ", i);
}
// Horizontal seprator
printf("\n---------------+--------------------------------------------------");
for(int i = 0; i < size; i++) {
addr = ((unsigned long)(ptr + i));
if((i == 0) && (addr & 0xF)) {
// Set the last digit of address as 0
printf("\n0x%lx | ", addr & ~(0xF));
// If the address is not starting from mod 16
// Add padding with 00 till the data
printf(" 00 00 00 00 00 00 00 00 ");
}
if(addr % 16 == 0) {
// Print address after every 16 bytes
printf("\n0x%lx | ", addr);
}
// A vertical line after 8 bytes
if(addr % 8 == 0) printf(" ");
// Print each bytes
printf("%02x ", *(unsigned char*)(ptr+i));
}
printf("\n\n");
}
@mshafeeqkn
Copy link
Author

Call this function to print the structure data in the memory.

Sample code

#include <stdio.h>
#include <stdint.h>

typedef struct {
    int m;
    long f;
} datatype;


int main() {
    datatype data = {0x12345678, 6};
    dump_structure(&data, sizeof(data));
    return 0;
}

The output of above code will be

Shafeeques-MacBook-Air:tmp$ ./main

                 0  1  2  3  4  5  6  7   8  9  a  b  c  d  e  f
-------------+--------------------------------------------------
7ff7b979d720 |  78 56 34 12 00 00 00 00  06 00 00 00 00 00 00 00

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment