Is it possible to save a memory address to a string?

You can try using a string format

char strAddress[] = "0x00000000"; // Note: You should allocate the correct size, here I assumed that you are using 32 bits address

sprintf(strAddress, "0x%x", &stuff);

Then you create your string from this char array using the normal string constructors


Here's a way to save the address of a pointer to a string and then convert the address back to a pointer. I did this as a proof of concept that const didn't really offer any protection, but I think it answers this question well.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    // create pointer to int on heap
    const int *x = new int(5);
        // *x = 3; - this fails because it's constant

    // save address as a string 
    // ======== this part directly answers your question =========
    ostringstream get_the_address; 
    get_the_address << x;
    string address =  get_the_address.str(); 

    // convert address to base 16
    int hex_address = stoi(address, 0, 16);

    // make a new pointer 
    int * new_pointer = (int *) hex_address;

    // can now change value of x 
    *new_pointer = 3;

    return 0;
}

You could use std::ostringstream. See also this question.

But don't expect the address you have to be really meaningful. It could vary from one run to the next of the same program with the same data (because of address space layout randomization, etc.)

Tags:

C++