title: Linux C: Easy & 'pretty' dump/printout of structs (like in gdb) - from source code?
body: <p>I am having a slight problem with some structs in a kernel module I'm building, so I thought it would be nice if there was an easy way to print out structs and their values - and below is a small userland example of what I mean.</p>
  
  <p>Say we have the simple C example as below (given in form of a bash commands):</p>
  
  <pre><code>FN=mtest
  
  cat &gt; $FN.c &lt;&lt;EOF
  #include &lt;stdio.h&gt; //printf
  #include &lt;stdlib.h&gt; //calloc
  
  struct person
  {
   int age; 
   int height; 
  };
  
  static struct person *johndoe;
  
  main ()
  {
  
   johndoe = (struct person *)calloc(1, sizeof(struct person));
   johndoe-&gt;age = 6; 
  
   asm("int3"); //breakpoint for gdb
  
   printf("Hello World - age: %d\n", johndoe-&gt;age);
  
   free(johndoe);
  }
  EOF
  
  gcc -g -O0 $FN.c -o $FN
  
  # just a run command for gdb
  cat &gt; ./gdbcmds &lt;&lt;EOF
  run
  EOF
  
  gdb --command=./gdbcmds ./$FN 
  </code></pre>
  
  <p>&nbsp;</p>
  
  <p>If we run this example, the program will compile, and gdb will run it, and automatically stop at the breakpoint. Here we can do the following:</p>
  
  <pre><code>Program received signal SIGTRAP, Trace/breakpoint trap.
  main () at mtest.c:20
  20  printf("Hello World - age: %d\n", johndoe-&gt;age);
  (gdb) p johndoe
  $1 = (struct person *) 0x804b008
  (gdb) p (struct person)*0x804b008
  $2 = {age = 6, height = 0}
  (gdb) c
  Continuing.
  Hello World - age: 6
  
  Program exited with code 0300.
  (gdb) q
  </code></pre>
  
  <p>&nbsp;</p>
  
  <p>As shown, in gdb we can printout (dump?) the value of the struct pointer <code>johndoe</code> as <code>{age = 6, height = 0}</code> ... I would like to do the same, but directly from a C program; say as in the following example: </p>
  
  <pre><code>#include &lt;stdio.h&gt; //printf
  #include &lt;stdlib.h&gt; //calloc
  #include &lt;whatever.h&gt; //for imaginary printout_struct
  
  struct person
  {
   int age; 
   int height; 
  };
  
  static struct person *johndoe;
  static char report[255]; 
  
  main ()
  {
  
   johndoe = (struct person *)calloc(1, sizeof(struct person));
   johndoe-&gt;age = 6; 
  
   printout_struct(johndoe, report); //imaginary command
  
   printf("Hello World - age: %d\nreport: %s", johndoe-&gt;age, report);
  
   free(johndoe);
  }
  </code></pre>
  
  <p>&nbsp;</p>
  
  <p>which would result with an output like:</p>
  
  <pre><code>Hello World - age: 6
  $2 = {age = 6, height = 0}
  </code></pre>
  
  <p>&nbsp;</p>
  
  <p>So my question is - does a function like that imaginary <code>printout_struct</code> exist - or is there another approach to make a printout like this possible? </p>
  
  <p>Thanks in advance for any help, <br/>
  Cheers!</p>