1

I am not sure how to get a string from an address in C++.

Pretend this is the address: 0x00020348 Pretend this address holds the value "delicious"

How would I get the string "delicious" from the address 0x00020348? Thank you.

1 Answers1

1

This answer is to help expand on our dialogue in the comments.

Please see the following code as an example:

#include <stdio.h>
#include <string.h>
#include <string>

int main()
{
    // Part 1 - Place some C-string in memory.
    const char* const pszSomeString = "delicious";
    printf("SomeString = '%s' [%08p]\n", pszSomeString, pszSomeString);

    // Part 2 - Suppose we need this in an int representation...
    const int iIntVersionOfAddress = reinterpret_cast<int>(pszSomeString);
    printf("IntVersionOfAddress = %d [%08X]\n", iIntVersionOfAddress, static_cast<unsigned int>(iIntVersionOfAddress));

    // Part 3 - Now bring it back as a C-string.
    const char* const pszSomeStringAgain = reinterpret_cast<const char* const>(iIntVersionOfAddress);
    printf("SomeString again = '%s' [%08p]\n", pszSomeStringAgain, pszSomeStringAgain);

    // Part 4 - Represent the string as an std::string.
    const std::string strSomeString(pszSomeStringAgain, strlen(pszSomeStringAgain));
    printf("SomeString as an std::string = '%s' [%08p]\n", strSomeString.c_str(), strSomeString.c_str());

    return 0;
}

Part 1 - The variable pszSomeString should represent the real string in memory you are trying to seek (an arbitrary value but 0x00020348 for sake of your example).

Part 2 - You mentioned that you were storing the pointer value as an int, so iIntVersionOfAddress is an integer representation of the pointer.

Part 3 - Then we take the integer "pointer" and restore it to a const char* const so that it can be treated as a C-string again.

Part 4 - Finally we construct an std::string using the C-string pointer and the length of the string. You wouldn't actually need the length of the string here since the C-string is null character ('\0')-terminated, but I'm illustrating this form of the std::string constructor in the event that you have to logically figure out the length yourself.

The output is as follows:

SomeString = 'delicious' [0114C144]
IntVersionOfAddress = 18137412 [0114C144]
SomeString again = 'delicious' [0114C144]
SomeString as an std::string = 'delicious' [0073FC64]

The pointer addresses will vary, but the first three hex pointer values are the same, as would be expected. The new string buffer constructed for the std::string version is a completely different address, also as would be expected.

Final note - knowing nothing about your code, a void* would normally be considered a better representation of a generic pointer than an int.

Phil Brubaker
  • 1,257
  • 3
  • 11
  • 14