[英]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.