我開始注意到,有時當我在某些程序中釋放內存時,它們會莫名其妙地崩潰。我開始縮小的罪魁禍首,並拿出那說明我有困難的理解時的例子:C++免費()更改其他內存
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
char *tmp = (char*)malloc(16);
char *tmp2 = (char*)malloc(16);
long address = reinterpret_cast<long>(tmp);
long address2 = reinterpret_cast<long>(tmp2);
cout << "tmp = " << address << "\n";
cout << "tmp2 = " << address2 << "\n";
memset(tmp, 1, 16);
memset(tmp2, 1, 16);
char startBytes[4] = {0};
char endBytes[4] = {0};
memcpy(startBytes, tmp - 4, 4);
memcpy(endBytes, tmp + 16, 4);
cout << "Start: " << static_cast<int>(startBytes[0]) << " " << static_cast<int>(startBytes[1]) << " " << static_cast<int>(startBytes[2]) << " " << static_cast<int>(startBytes[3]) << "\n";
cout << "End: " << static_cast<int>(endBytes[0]) << " " << static_cast<int>(endBytes[1]) << " " << static_cast<int>(endBytes[2]) << " " << static_cast<int>(endBytes[3]) << "\n";
cout << "---------------\n";
free(tmp);
memcpy(startBytes, tmp - 4, 4);
memcpy(endBytes, tmp + 16, 4);
cout << "Start: " << static_cast<int>(startBytes[0]) << " " << static_cast<int>(startBytes[1]) << " " << static_cast<int>(startBytes[2]) << " " << static_cast<int>(startBytes[3]) << "\n";
cout << "End: " << static_cast<int>(endBytes[0]) << " " << static_cast<int>(endBytes[1]) << " " << static_cast<int>(endBytes[2]) << " " << static_cast<int>(endBytes[3]) << "\n";
free(tmp2);
return 0;
}
這裏是我看到的輸出:我使用
tmp = 8795380
tmp2 = 8795400
Start: 16 0 0 0
End: 16 0 0 0
---------------
Start: 17 0 0 0
End: 18 0 0 0
Borland的免費編譯器。我知道,我正在看的頭字節是特定於實現的,像「reinterpret_cast」這樣的東西是不好的做法。我只想找到答案的問題是:爲什麼「結束」的第一個字節從16更改爲18?
被認爲「結束」的4個字節是tmp之後的16個字節,它們是tmp2之前的4個字節。它們是tmp2的頭文件 - 爲什麼在tmp上調用free()會影響內存中的這個地方?
我嘗試過使用new []和delete []創建/刪除tmp和tmp2的相同示例,並且會出現相同的結果。
任何信息或幫助理解爲什麼這個特定的地方在記憶中受到影響將不勝感激。
不相關,但C++程序員應該使用new和delete(或new []和delete []),而不是malloc和free。 – 2011-02-24 22:32:10
更普遍的是,如果你使用'new []'和'delete []',你可能真的需要'std :: vector'。 – birryree 2011-02-24 22:35:19
我不能再給J.N.的+1評論,但如果我能的話,我會! – corsiKa 2011-02-24 22:35:51