嘗試運行以下代碼時出現運行時錯誤。
- 函式 get() 回傳一個存盤用戶輸入的空指標。
- 函式 getShort() 呼叫 get() 函式并在回傳其值之前對指標進行型別轉換并取消對 short 的參考。
- 雖然該值在 getShort(); 中作業得非常好;任何其他呼叫它的方法都會得到以下運行時錯誤。
The instruction at Ox000000000040002C referenced memory at Ox000000000000002C. The memory could not be written.
void * get(char formatSpecifier[]){
void *ptr;
scanf(formatSpecifier, ptr);
return ptr;
}
int getInt(){
int i = *(int *)get("%d");
printf("Works perfectly fine here: %d", i);
return i;
}
int main(){
int j = getInt(); // Error thrown here.
prinf("The value is : %d", j); // Does not print;
return 0;
}
任何幫助或反饋表示贊賞。非常感謝。
uj5u.com熱心網友回復:
正如nm所說,在第 3 行,scanf(formatSpecifier, ptr);您使用了一個未初始化的指標。void *ptr;未初始化,這意味著您沒有決定它指向的位置,但隨后嘗試使用它,嘗試在無法訪問的記憶體上寫入錯誤
Ox000000000040002C 處的指令參考了 Ox000000000000002C 處的記憶體。無法寫入記憶體。
指出。在這種情況下,Ox000000000040002C 是您的 ptr 的索引,而 Ox000000000000002C 是它指向的索引(它可能會有所不同,因為您沒有初始化您的指標)。
我相信你可以在這里閱讀更多內容。
旁注:在您的問題中,您解釋了一個函式 GetShort() 但在提供的代碼中使用了一個函式 GetInt() 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532297.html
標籤:C指针运行时错误
上一篇:熊貓列中按升序排序的問題
