24

I am trying to print a struct that is coming as an argument in a function in order to do some debugging.

Is there anyway I could print a structure's contents without knowing what it looks like, i.e. without printing each field explicitly? You see, depending on loads of different #defines the structure may look very differently, i.e. may have or not have different fields, so I'd like to find an easy way to do something like print_structure(my_structure).

NetBeans' debugger can do that for me, but unfortunately the code is running on a device I can't run a debugger on.

Any ideas? I suppose it's not possible, but at least there may be some macro to do that at compilation time or something?

Thanks!

Albus Dumbledore
  • 12,368
  • 23
  • 64
  • 105
  • 1
    This is now possible in the clang compiler. See [my response to a similar question](https://stackoverflow.com/a/58721823/219710). (Not sure if SO etiquette is to post a duplicate answer here, or link to the other one) – Jonathan Fuerth Nov 18 '19 at 01:03

2 Answers2

28

You can always do a hex dump of the structure:

#define PRINT_OPAQUE_STRUCT(p)  print_mem((p), sizeof(*(p)))

void print_mem(void const *vp, size_t n)
{
    unsigned char const *p = vp;
    for (size_t i=0; i<n; i++)
        printf("%02x\n", p[i]);
    putchar('\n');
};
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • This code will also display the contents of the padding bytes. They may contain any value and may be located anywhere inside the struct. – Lundin Mar 18 '11 at 09:13
  • 1
    @Lundin: that's true. But with some knowledge of the compiler, this may still contain useful information. You'd have to know where to look. – Fred Foo Mar 18 '11 at 09:14
  • when I compile this function,it tells print_struct.cpp: In function ‘void print_mem(const void*, size_t)’: print_struct.cpp:14:30: error: invalid conversion from ‘const void*’ to ‘const unsigned char*’ [-fpermissive] – kuafu Jun 08 '13 at 15:04
  • 1
    @young001: that's because it's written in C. In C++, you need an explicit cast to `unsigned char const *`. – Fred Foo Jun 08 '13 at 19:16
  • 1
    slight better, with grouping and line wrapping: `printf("%02x%s", p[i], i==0 ? "" : i % 16 == 15 ? "\n" : i % 4 == 3 ? " " : "");` – sehari24jam Sep 10 '15 at 06:30
  • 3
    I strongly disagree with the notion that cramming multiple ternary operators into a parameter is "better." – 3Dave Nov 29 '16 at 14:41
3

There is nothing like RTTI in C, only solution (apart from hex dump like above) is to #define dump function together with other #defines, ie.

#if _DEBUG

struct { ..... }
#define STRUCT_DUMP(x) printf(.....)

#else

struct { ..... } // other version
#define STRUCT_DUMP(x) printf(.....)    // other version dump

#endif
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
pma_
  • 810
  • 1
  • 8
  • 9