programing

C에서 메모리 주소를 인쇄하는 방법

yoursource 2022. 12. 21. 23:08
반응형

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);

표준에서는 인수가 유형이어야 합니다.void*위해서%p지정자.부터,printf에 대한 암묵적인 변환은 없습니다.void *부터T *C의 모든 비변수 함수에 대해 암묵적으로 발생합니다.따라서 캐스팅이 필요합니다.표준을 인용하려면:

7.21.6 형식화된 입출력 기능(C11 드래프트)

p 인수는 무효의 포인터가 된다.포인터의 값은 구현 정의 방식으로 일련의 인쇄 문자로 변환됩니다.

사용하시는 동안%x(예상)unsigned int반면에.&A종류int *매뉴얼에서 printf 형식 지정자에 대해 읽어보실 수 있습니다.printf 형식 지정자가 일치하지 않으면 정의되지 않은 동작이 발생합니다.

사용하는 회피책%x인쇄하는 길이 지정자를 사용하여int또는unsigned 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);

언급URL : https://stackoverflow.com/questions/30354097/how-to-printf-a-memory-address-in-c

반응형