如何在C中打印内存地址

How to printf a memory address in C

我的代码是:

#include <stdio.h>
#include <string.h>

void main()
    {
    char string[10];
    int A = -73;
    unsigned int B = 31337;

    strcpy(string, "sample");

    // printing with different formats
    printf("[A] Dec: %d, Hex: %x, Unsigned: %u\n", A,A,A);
    printf("[B] Dec: %d, Hex: %x, Unsigned: %u\n", B,B,B);
    printf("[field width on B] 3: '%3u', 10: '%10u', '%08u'\n", B,B,B);

    // Example of unary address operator (dereferencing) and a %x
    // format string 
    printf("variable A is at address: %08x\n", &A);

我正在使用 linux mint 中的终端进行编译,当我尝试使用 gcc 进行编译时,我收到以下错误消息:

basicStringFormatting.c: In function ‘main’:
basicStringFormatting.c:18:2: warning: format ‘%x’ expects argument
of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("variable A is at address: %08x\n", &A);

我要做的就是打印变量 A 在内存中的地址。

使用格式说明符%p:

printf("variable A is at address: %p\n", (void*)&A);

标准要求对于 %p 说明符,参数是 void* 类型。由于 printf 是可变参数函数,因此不存在从 T *void * 的隐式转换,这对于 C 中的任何非可变参数函数都会隐式发生。因此,需要强制转换。引用标准:

7.21.6 格式化 input/output 函数(C11 草案)

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

而您使用的是 %x,它需要 unsigned int,而 &Aint * 类型。您可以阅读 printf from the manual. Format specifier mismatch in printf leads to undefined behaviour 的格式说明符。

使用带有长度说明符的 %x 来打印 intunsigned int 而编译器不会抱怨转换的变通方法是使用 malloc:

unsigned int* D = malloc(sizeof(unsigned int)); // Allocates D
unsigned int D_address = *((unsigned int*) &D); // D address for %08x without warning
*D = 75; // D value
printf("variable D is at address: %p / 0x%08x with value: %u\n", D, D_address, *D);

或者,您可以使用 gcc -w 标志进行编译以抑制这些转换警告。

编辑 64 位地址:

unsigned long* D = malloc(sizeof(unsigned long)); // Allocates D
unsigned long D_address = *((unsigned long*) &D); // D address for %016lx without warning
*D = ULONG_MAX; // D value
printf("variable D is at address: %p / 0x%016lx with value: %lu\n", D, D_address, *D);