c++中从十六进制转换为无符号int*

Cast from hexadecimal to unsigned int* in c++

本文关键字:无符号 int 转换 十六进制 c++      更新时间:2023-10-16

我有一个赋值,应该在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;
}