c++中从十六进制转换为无符号int*
Cast from hexadecimal to unsigned int* in c++
我有一个赋值,应该在C/c++中评估一些指针操作表达式和内存泄漏情况。有一个我无法摆脱:
unsigned int* pInt = (unsigned int*) 0x403004;
一开始这对我来说是可疑的,但在赋值中,这一行理论上是工作的,但是运行程序时,我在这一行得到了段错误。
问题是:这是正确的,甚至是可能的,或者教授只是在欺骗我们,告诉我们这是正确的?我看到过一些将字符串"hex"转换为int的例子和问题,但没有关于"纯hex"转换为int或int*
unsigned int* pInt = (unsigned int*) 0x403004;
这里有两点值得怀疑:
除非你正在编写一些专门的软件,如设备驱动程序或操作系统,或者你在一些嵌入式或特殊的系统中,内存是固定的,看到内存地址硬编码肯定是可疑的。如果您的程序试图访问它没有访问权限的内存,它将(充其量)失败。
在右边,编译器首先将
0x403004
的值推断为int
中的值,并将其正确转换为指针。因此,您的段故障可能是第一个点的结果。
unsigned int* pInt = (unsigned int*) 0x403004;
可能吗?: yes(编译和构建都很好)
正确吗?那要看为什么。显然,它在课堂作业中很有用。
推荐吗?不。它将调用未定义行为。您正在创建一个变量,该变量指向您可能有权也可能无权访问的内存中的某个位置。如果你从不使用它,没关系。但是如果你使用它,结果是不确定的。
仅当该数字表示已分配的内存时才正常工作如:
#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;
}
相关文章:
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 是否可以将无符号 int 的最大值转换为 int 并将结果转换为 -1?
- 为什么QByteArray的大小是"int"而不是"无符号int"
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- 使用无符号int作为二进制来在c++中实现一个集
- C++如何将变量传递给带有无符号 int & 的参数uint16_t函数?
- 为什么我不能使用在 Visual C++ 32 位中实现运算符无符号 int() 作为数组索引的类?
- 视觉C++转换和写入值为 10 的无符号 int 给出 5 个字节
- uint8_t在转换为无符号 int 时未打印正确的值
- G++ 错误:重载的"abs(无符号 int)"的调用不明确
- 将 3D 矢量浮点打包到无符号 int 中并将其解压缩
- 如何使用 JNI 将 double 和无符号 int 从本机 c 库返回到 java
- 为什么printf和cout为此无符号int提供了不同的输出
- memcpy 从无符号字符 * 到无符号 int
- C++ 重载与有符号和无符号 int 不同
- 创建具有未定义溢出的无符号 int
- 将大双精度转换为无符号 int 期间堆栈损坏
- 错误:成员引用基类型"uint32_t"(也称为"无符号 INT")不是结构或联合
- 无符号int的比较始终是正确的(NPOS问题?)