英文:
C++: get value of memory address from a text file
问题
以下是翻译好的部分:
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;
temp.open("temp.txt");
string address;
getline(temp, address);
temp.close();
std::cout << *reinterpret_cast<double*>(strtoull(address.c_str(), NULL, 16)) << std::endl;
That does not work --> "cannot convert std::string to const char *"
Any help much appreciated!
英文:
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;
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!
答案1
得分: 1
您的strtoul()
调用有三个问题:
-
它接受C风格的以null结尾的
const char*
字符串作为输入,而不是std::string
对象。这就是您看到的编译器错误的原因。可以使用std::string::c_str()
方法或std::stoul()
函数来解决这个问题。 -
它返回一个整数,而不是一个指针。使用
reinterpret_cast
来解决这个问题。 -
它返回的整数值可能适合也可能不适合作为指针,这取决于这段代码运行在哪个平台。因此,您可能会截断结果指针。在64位系统上运行时,请使用
std::strtoull()
。
可以尝试这样改写代码:
std::ifstream ifs("temp.txt");
std::string str;
std::getline(ifs, str);
ifs.close();
uintptr_t address = std::strtoul(str.c_str(), NULL, 16); // 或者使用 std::strtoull()
double *pdbl = reinterpret_cast<double*>(address);
std::cout << *pdbl << std::endl;
不过,您也可以考虑使用operator>>
,因为它有一个用于读取指针的重载,例如:
std::ifstream ifs("temp.txt");
void* address;
ifs >> address;
ifs.close();
double *pdbl = static_cast<double*>(address);
std::cout << *pdbl << std::endl;
英文:
Your call to strtoul()
is wrong for 3 reasons:
-
it takes a C-style null-terminated
const char*
string as input, not astd::string
object. Hence the compiler error you are seeing. Use thestd::string::c_str()
method, or thestd::stoul()
function, to solve this. -
it returns an integer, not a pointer. Use)reinterpret_cast` to solve this.
-
the integer value it returns may or may not fit in a pointer, depending on which platform this code is running on. So, you are risking truncating the resulting pointer. Use
std::strtoull()
when running on a 64-bit system.
Try this instead:
std::ifstream ifs("temp.txt");
std::string str;
std::getline(ifs, str);
temp.close();
uintptr_t address = std::strtoul(str.c_str(), NULL, 16); // or std::strtoull()
double *pdbl = reinterpret_cast<double*>(address);
std::cout << *pdbl << std::endl;
That being said, consider using operator>>
instead, as it has an overload for reading in a pointer, eg:
std::ifstream ifs("temp.txt");
void* address;
ifs >> address;
ifs.close();
double *pdbl = static_cast<double*>(address);
std::cout << *pdbl << std::endl;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论