How to print memory as hex to console, syslog, kernellog.
I couldn't find a good implementation of a simple debugging function which prints an array to the console, syslog and the kernel log. So i made one.
Currently I am developing Linux Kernel modules and normal user-mode applications in parallel. I needed a function which prints the content of a char array to the console, the syslog and the kernel log. Finding such function via google was difficult. In the end I did some thinkering and implemented a function on my own.
If you use the function in your project you have to enable / disable the corresponding printf / syslog / printk line.
The implementation is straight forward. You call the function with mem, the address of the first byte you want to print, and define the number of bytes you want to print with count. I choosed
An example could look like this:
It seems strange that the output is the same regardless of calling the functions with the array or its address. But thats exactly what the compiler is doing, it uses the adress of the array in the function call.
This gets interesting when calling the function with an char pointer array:
Pointer to array of pointers
On Stackexchange someone proposed an initialization of a char array the following way. I copied it without thinking and was highly confused about the result of the printMemory function.
Instead of defining a normal char array he defined a char pointer array.
Okay, at first we get the gcc notice that our argument is not a char pointer but a char pointer pointer. The result can be seen in the output. We get the first byte 0x6B then 7 zero’s then the next byte 0xC1.
So what is happening here. The initialization of the char pointer array means that gcc saves pointers in the 64 fields of
ptest_plain_text instead of actual char vars. One pointer is 8 byte long. These saved pointers should point to char variables. The given bytes (0x6b,0xc1,0xbe, ..) are interpreted as pointer addresses to these char variables.
This interpretation is nonsense and not that what the user on stackoverflow wanted. He wanted a simple char array. Instead he got a pointer to an array of pointers which point to chars at impossible adresses. If you call
*ptest_plain_text to get the char value, your computer tries to access the value at adress 00 00 00 00 00 00 00 6B and retrieves a segmentation fault.
So if you get strange segmentation faults in the future, simply debug your program and have a look at the actuall memory. In kernel-space it is more difficult to debug because the kernel halts if you run in a segmentation fault and you are unable to have a look at the memory. This print memory function will help you to debug your arrays hopefully before the kernel halts.