0 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;
}
Run Code Online (Sandbox Code Playgroud)
这是我看到的输出:
tmp = 8795380
tmp2 = 8795400
Start: 16 0 0 0
End: 16 0 0 0
---------------
Start: 17 0 0 0
End: 18 0 0 0
Run Code Online (Sandbox Code Playgroud)
我正在使用Borland的免费编译器.我知道我正在查看的头字节是特定于实现的,像"reinterpret_cast"这样的东西是不好的做法.我只想找到答案的问题是:为什么"结束"的第一个字节从16变为18?
被认为是"结束"的4个字节是tmp之后的16个字节,它们是tmp2之前的4个字节.它们是tmp2的标题 - 为什么在tmp上调用free()会影响内存中的这个位置?
我尝试了使用new []和delete []来创建/删除tmp和tmp2的相同示例,并且会出现相同的结果.
任何信息或帮助,以了解为什么这个特定的地方在记忆中受到影响将非常感激.