恢復到以前的值在存儲區中我打了使用C一點點,寫了下面的代碼:用C
#include<stdio.h>
#include<stdlib.h>
int main() {
char* value = malloc(5 * sizeof(char));
int vect[3];
printf("%d\n", value[135151]);
int i, count = 0;
for(i = 0; i < 135152; i++) {
if(value[i]) {
count++;
printf("position is %d, value is %d and i change it with 42\n", i, value[i]);
value[i] = 42;
vect[count - 1] = i;
}
}
printf("count is %d\n", count);
printf("pointer is at location %p\n", value);
printf("changed values are %d %d %d\n", value[vect[0]], value[vect[1]],
value[vect[2]]);
return 0;
}
多次嘗試後,我的筆記本電腦,我發現,如果我打印值[135152]我得到 段錯誤,如果我打印值[135151]我得到0在標準輸出。
之後,我很好奇 發現如果在此區間中有非零值,並顯示3個非零值。然後,我嘗試將它們全部修改爲42(我忘了提及在很多程序執行時,即使向量值顯示在不同的位置,如0xbe7010或0x828010,也是如此在相同的位置保留非零值,這使我明白指針地址是虛擬的(但位置相同))。
之後,我修改了這些值,我最後打印了它們以確保它們,並且它們顯示了它們全部3個。但是,在另一個程序執行中,顯示了以前的值,就像我沒有修改該內存區域一樣。
我會給你我的連續3個輸出:
0
position is 24, value is -31 and i change it with 42
position is 25, value is 15 and i change it with 42
position is 26, value is 2 and i change it with 42
count is 3
pointer is at location 0x21bb010
changed values are 42 42 42
0
position is 24, value is -31 and i change it with 42
position is 25, value is 15 and i change it with 42
position is 26, value is 2 and i change it with 42
count is 3
pointer is at location 0x20d1010
changed values are 42 42 42
0
position is 24, value is -31 and i change it with 42
position is 25, value is 15 and i change it with 42
position is 26, value is 2 and i change it with 42
count is 3
pointer is at location 0x19d0010
changed values are 42 42 42
能否請你告訴我,爲什麼還要改變後的值是否仍然存在?
而且,爲什麼指針地址改變,但內存區域是一樣的? (我懷疑C中的物理和虛擬內存之間存在雙向函數,每次執行程序時都會發生變化)。
感謝您的幫助,併爲此牆文本感到抱歉!
代碼應該總是檢查malloc(和系列)返回的值以確保操作成功 – user3629249
這一行:'printf(「%d \ n」,value [135151]);'正在訪問分配區域之外的內存。這會導致未定義的行爲,導致seg故障事件。 – user3629249
這一行:'if(value [i]){'當'i'大於4時,會導致未定義的行爲,導致seg故障事件。未定義行爲執行時會發生什麼是'未定義'。這可能是任何事情,包括你所看到的行爲。注意:在同一個循環中還有兩個未定義行爲的實例。而不是擔心一些隨機事件是可重複的,更好地修復程序。 – user3629249