代码中的堆损坏 根据VisualC++运行时,析构函数中调用空闲时存在堆损坏。但我不明白为什么会出现堆损坏,有人能解释为什么吗?精确误差为: CRT detected that the application wrote to memory after end of heap buffer.
另外,如果忽略错误,程序不会崩溃,它会继续运行,当我按下一个键时,它返回0 该类仅包含构造函数和析构函数以及私有变量代码中的堆损坏 根据VisualC++运行时,析构函数中调用空闲时存在堆损坏。但我不明白为什么会出现堆损坏,有人能解释为什么吗?精确误差为: CRT detected that the application wrote to memory after end of heap buffer.,c++,c,memory,heap-corruption,C++,C,Memory,Heap Corruption,另外,如果忽略错误,程序不会崩溃,它会继续运行,当我按下一个键时,它返回0 该类仅包含构造函数和析构函数以及私有变量FILE*target和char*raw_data foo::foo (wchar_t* path) { size_t size; target = _wfopen (path, L"rb+"); if (!target) { char* error = strerror (errno); printf ("The file
FILE*target
和char*raw_data
foo::foo (wchar_t* path)
{
size_t size;
target = _wfopen (path, L"rb+");
if (!target) {
char* error = strerror (errno);
printf ("The file could not be opened: %s\n", error);
_exit (1);
}
fseek (target, 0L, SEEK_END);
size = ftell (target);
fseek (target, 0, SEEK_SET);
raw_data = (char*) malloc (size);
size = fread (raw_data, 1, size, target);
raw_data[size] = '\0';
}
foo::~foo ()
{
fclose (target);
free (raw_data);
}
int main ()
{
nbt* klas = new nbt (L"C:\\Users\\Ruben\\level");
puts ("Success?!");
delete klas;
getchar ();
return 0;
}
在编写
NUL
终止符时:
raw_data[size] = '\0';
。。。您使用的字节比分配的字节多一个字节。可能还有其他错误,但这一行肯定有错误——写入未分配的内存是“未定义的行为”,可以解释您正在观察的崩溃。一个确定的问题是以下代码:
raw_data = (char*) malloc (size);
size = fread (raw_data, 1, size, target);
raw_data[size] = '\0';
您无法访问原始数据[size]
,因为它超出了分配的大小。C/C++中的索引访问是基于零的。因此,可以使用现有代码访问的raw_data
的最后一个元素是raw_data[size-1]
。为了能够将偏移量大小
处的字节设置为零,您需要将malloc
更改为:
raw_data = (char*) malloc (size+1);
因为这是一个C++应用程序,你可能想使用流和NeX/Delphi来代替文件指针和MalC/C。< /P>“如果我忽略了错误,程序不会崩溃,它会继续运行”,所以这里没有崩溃,但是答案仍然成立,甚至更多。在未定义的行为范围内,任何事情都可能发生。谢谢,这解决了问题。我使用malloc,因为我以后可能需要重新定位数据。