我开始注意到,有时当我在某些程序中释放内存时,它们会莫名其妙地崩溃。我开始缩小的罪魁祸首,并拿出那说明我有困难的理解时的例子: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