Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to printf a memory address in C

My code is:

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

I am using the terminal in linux mint to compile, and when I try to compile using gcc I get the following error message:

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

All I am trying to do is print the address in memory of the variable A.

like image 494
varlotbarnacle Avatar asked May 20 '15 15:05

varlotbarnacle


People also ask

How do I print a memory address of a pointer?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

How can we get its address in memory in C?

When a variable is created in C, a memory address is assigned to the variable. The memory address is the location of where the variable is stored on the computer. When we assign a value to the variable, it is stored in this memory address.

How do you print the address of a function in C?

Without using the separate pointer for print the address of the function, You can use the name of the function in the printf . printf("The address of the function is =%p\n",test); For printing the address in the hexa-decimal format you can use the %p .


1 Answers

Use the format specifier %p:

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

The standard requires that the argument is of type void* for %p specifier. Since, printf is a variadic function, there's no implicit conversion to void * from T * which would happen implicitly for any non-variadic functions in C. Hence, the cast is required. To quote the standard:

7.21.6 Formatted input/output functions (C11 draft)

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.

Whereas you are using %x, which expects unsigned int whereas &A is of type int *. You can read about format specifiers for printf from the manual. Format specifier mismatch in printf leads to undefined behaviour.

like image 63
P.P Avatar answered Sep 25 '22 04:09

P.P