Warm tip: This article is reproduced from stackoverflow.com, please click
c driver linux-device-driver linux-kernel

Difference between %llx and %p while printing a pointer inside driver code

发布于 2020-05-11 04:27:24

It seems that casting a void* pointer (allocated by kmalloc) to unsigned long long changes it. Printing them with %p and %llx gives different values. Why is it so? Can anyone explain?

Following is a simple repro for that:

#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>

void* kbuff;
int init_module(void)
{

    kbuff = kzalloc(sizeof(char), GFP_KERNEL);
    pr_info("%p %llx\n",kbuff, (unsigned long long)kbuff);
    return 0;
}

void cleanup_module(void)
{
    kfree(kbuff);
}

The dmesg output comes out to be as follows

[67355.673465] 000000003aeb0247 ffff9ef657a58c00
Questioner
atuly
Viewed
34
Ctx 2020-02-26 19:15

From the documentation of printk() (which pr_info calls):

Pointer Types

Pointers printed without a specifier extension (i.e unadorned %p) are hashed to give a unique identifier without leaking kernel addresses to user space. On 64 bit machines the first 32 bits are zeroed. If you really want the address see %px below.

So, this is a security measure. Use the %px format specifier to print the real address (which should match now)