Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what I tried:

std::fstream temp;
temp.open("temp.txt");
string address;
getline(temp, address);
temp.close();
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;
temp.open("temp.txt");
std::string address;
std::getline(temp, address);
temp.close();
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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading