Usam
Usam

Reputation: 103

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

Upvotes: 0

Views: 914

Answers (2)

Andrew Henle
Andrew Henle

Reputation: 1

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.

Upvotes: 4

tdao
tdao

Reputation: 17668

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

Upvotes: 3

Related Questions