C++: get value of memory address from a text file

I have a text file with a single line that stores the memory address to a variable (of type double) being used in the code.

Content of temp.txt: 0x7f3c00844c00

I would like to read this line and dereference it to get the double value stored at the address (i.e. 0x7f3c00844c00)

This is what I tried:

std::fstream temp;
string address;
getline(temp, address);
std::cout << *strtoul(address, NULL, 16) << std::endl;

That does not work –> "cannot convert std::string to const char *"

Any help much appreciated!

>Solution :

Your fixed code

Here is the fixed code:

std::fstream temp;
std::string address;
std::getline(temp, address);
double* ptr = reinterpret_cast<double*>(strtoul(address.c_str(), NULL, 16));
std::cout << *ptr << std::endl;

The changes are to use the c_str() function to change the ptr variable to const char * because that is the type that stroutl uses, then it casts the what it returned from the strtoutl (a void*) to a double* then uses cout to output the double* (ptr).

Why you shouldn’t do this

Upon running your program, it’s place in memory changes, so the address of the variable will not always be the same. Unless the writing of the address and the reading of the address take place in the same program you will just get a garbled pointer to nothing and a segfault.

Leave a Reply