简体   繁体   中英

Cast from hexadecimal to unsigned int* in c++

I have an assignment that were supposed to evaluate some pointer manipulation expressions and memory leak situations in C/C++. There's one I'm stuck with:

unsigned int* pInt = (unsigned int*) 0x403004;

Right off the bat this is suspicious to me, but in the assignment this line is theoretically working, however running the program I'm get segfault right at this line.

The question is: Is this right or even is possible or the professor is just fooling us telling this is right? I've seen some examples and questions with string "hex" to int, but nothing regarding "pure hex" to int or int*

unsigned int* pInt = (unsigned int*) 0x403004;

Two things are suspicious here:

  • Unless, you are writing some specialized Software like device drivers or OS, or you are in some embedded or special system where memory is fixed, seeing memory address hardcoded is certainly suspicious. Your program will (at best) fail if it tries to access memory it doesn't have the access rights to.

  • On the right hand side, the compiler first deduces the value 0x403004 as in int and will correctly convert it to a pointer. Thus, your Segfault is probably as a result of the first point.

unsigned int* pInt = (unsigned int*) 0x403004;

Possible?: yes (compiles, builds just fine)

Is it right?: depends on what for. Evidently it is useful for illustration in a classroom assignment.

Is it recommended? no. It will invoke undefined behavior . You are creating a variable that points to a location in memory that you may or may not have rights to. If you never use it, fine. But if you do use it, the results are indeterminate.

it works fine only if that number represents an already allocated memory eg:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM