[英]Cast from hexadecimal to unsigned int* in c++
我有一个作业,应该对C / C ++中的一些指针操作表达式和内存泄漏情况进行评估。 我有一个坚持:
unsigned int* pInt = (unsigned int*) 0x403004;
马上,这对我来说是可疑的,但是在分配中,这条线在理论上是可行的,但是在运行该程序时,我在这条线上遇到了段错误。
问题是:这是正确的,甚至是可能的,还是教授只是在愚弄我们说这是正确的? 我已经看到了一些示例和带有int字符串“ hex”的问题,但没有任何关于将“ pure hex”字符串转换为int或int *的信息
unsigned int* pInt = (unsigned int*) 0x403004;
这里有两点可疑:
除非您正在编写某些专用软件(例如设备驱动程序或OS),或者您在某个固定内存的嵌入式系统或专用系统中,否则看到硬编码的内存地址肯定是可疑的。 如果您的程序尝试访问没有访问权限的内存,则(最多)该程序将失败。
在右侧,编译器首先将值0x403004
为int
,并将其正确转换为指针。 因此,您的Segfault可能是第一点的结果。
无符号整数* pInt =(无符号整数*)0x403004;
可能吗?:是(编译,构建就可以了)
是吗?:取决于目的。 显然,这对于课堂作业中的插图很有用。
推荐吗? 没有。 它将调用未定义的行为 。 您正在创建一个变量,该变量指向您在内存中可能有或没有权限的位置。 如果您从不使用它,那很好。 但是,如果您确实使用它,结果将是不确定的。
仅当该数字表示已分配的内存时,它才能正常工作,例如:
#include <iostream>
int main()
{
int i = 7;
std::cout << "i: " << i << std::endl; // 7
std::cout << "&i: " << &i << std::endl; // in my case: 0018FF44
unsigned int* ptr = (unsigned int*)0x0018FF44; // it's ok
/*
this is just for explaining because the address of i may differ at anytime the program
launches thus 0018FF44 will no longer be assigned to i and consequently segfault.
the right thing is to make pointer points always to whatever i may take as an address.
to do so:
*/
//int* ptr = (unsigned int*)&i; // not i but the address of i
(*ptr)++;
std::cout << i << std::endl; // 8
// above we changed i through pointer ptr
int* pRandom = (int*)0xAB2FC0DE0; // this causes me segfault
*pRandom = 5; // segfault
std::cout << "*pRandom: " << *pRandom << std::endl; // segfault
std::cout << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.