简体   繁体   中英

How to convert a memory address into a char string

I want to convert an address of a memory segement into char string.

Here is an example of code:

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    int size = 20;
    char buffer[10];
    char *ptr = (char*) malloc(size);
    printf("Ptr addr: %p\n", ptr);
    if(ptr != NULL)
    {
        snprintf(buffer, "%p", ptr);
        printf("Ptr addr stored in buffer: %p\n", buffer);
    }
    return EXIT_SUCCESS;
}

output:

Ptr addr: 0x55ab2a43e260

Ptr addr stored in buffer: 0x7ffe9a76470e

Unfortunatelly, I have two different addresses when I use the approach from my example code. Can please someone tell me what I'm doing wrong?

Best regards, Usam

This code prints the address of buffer , not what's in it:

printf("Ptr addr stored in buffer: %p\n", buffer);

You probably want

printf("Ptr addr stored in buffer: %s\n", buffer);

given that the previous code populated buffer with the string representation of the contents of ptr .

And as noted in the comments, your call to snprintf() isn't correct. It should be

    snprintf(buffer, sizeof(buffer), "%p", (void *) ptr);

Note the cast to (void *) - the %p format specifier requires a void * pointer.

buffer might also need to be longer than 10 bytes, depending on your system.

Two errors in your code

1) Wrong snprint - you missed the 2nd parameter which is the size of the buffer.

snprintf(buffer, sizeof(buffer), "%p", ptr);

2) Wrong format to print the buffer - it should be %s for string

printf("Ptr addr stored in buffer: %s\n", buffer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM