Question

if I have a pointer to int , and it's value is 0x0012FF7C how can I store this value in a string , and then make the reverse ( I mean convert the value stored in string to int*)

I need this way because I need to send a memory location between two process in PVM, so I need to send the value of a pointer as a string, and receive this string in the second process and store it's value in a pointer

Was it helpful?

Solution

Your plan doesn't sound like it's going to work, since a valid memory address in one process might be an invalid memory address in another process... Nevertheless, here is how you can do it:

  • In the first process, call sprintf(str,"%p",ptr)
  • In the second process, call sscanf(str,"%p",&ptr)
  • On a 32-bit system, you'll need to declare char str[8+1]
  • On a 64-bit system, you'll need to declare char str[16+1]

Having said that, you probably need to send the contents of the memory address, or if too long for this purpose, then write them into a file in one process and read them from that file in the other process.

OTHER TIPS

This should work to convert to string:

std::size_t i = 0x0012FF7C;
std::ostringstream buffer;
buffer << std::setw(size_t(void*)) << std::setfill('0') << std::hex << i;
assert(buffer.str() == "0012FF7C");

For the reading you can use a std::istringstream in a similar way (though I think you need to read as a string, then convert it to an int depending on the base).

That said, your question makes abstraction of address virtualization (depending where you run your code and under which conditions, it may not work).

Bufferoverflow-safe, old school C version:

  char addr[0xf];
  snprintf(addr, 0xf, "0x%X", ptr);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top