调试断言失败的缓冲区!=nullptr



这是我的代码:

ifstream ifile;
list<unsigned char> fbinary;
ifile.open(filename, ios::binary);
if (ifile.fail() || !ifile.is_open())
return false;
ifile.seekg(0, ios::end);
int sz = ifile.tellg();
if (sz <= 0)
return false;
try
{
//Get Binary And Encrypt with XOR
ifile.seekg(0, ios::beg);
unsigned char temp = 0;
while (ifile)
{
ifile.read((char*)temp, sizeof(unsigned char));
temp ^= Encrypt_Key;
fbinary.push_back(temp);
}
ifile.close();
}
...

file.open和获取文件大小不会失败。我不知道ifile.read()为什么激发调试断言。

错误消息:

表达式:缓冲区!=nullptr

buffer是什么还不清楚(它可能是标准库实现中的一个变量(,但问题中的代码至少有一个明显的错误:

unsigned char temp = 0;
... 
ifile.read((char*)temp, sizeof(unsigned char));

在这里,您首先用零初始化temp,然后将其转换为指针,这实际上是一个空指针。使用空指针调用.read()是UB-位置(char*)temp (= nullptr)没有有效的内存缓冲区。

你想要的可能是:

char temp;
... 
ifile.read(&temp, sizeof(char));

在这里,您将temp的有效地址传递给.read()

还要注意,从tellg()获取文件大小可能会给出不正确的结果。请参阅此问题。

在Try块内寻找开始之前,尝试调用ifile.clear((:

尝试{//呼叫清除ifile.clear((;//获取二进制并用XOR加密ifile.seekg(0,ios:beg(;无符号字符temp=0;while(ifile({

最新更新