使用 ifstream 时出现无效空指针错误
Invalid null pointer error when using ifstream
所以我在这段代码中有这个奇怪的"invalid null pointer"异常(切入问题的核心)
#include <fstream>
#include <iostream>
#include <iomanip>
int main(){
std::ifstream input;
std::ofstream output;
unsigned __int16 currentWord = 0;
output.open("log.txt");
input.open("D:\Work\REC022M0007.asf", std::ios::binary);
input.seekg(0, input.end);
int length = input.tellg();
input.seekg(0, input.beg);
for (int i = 0; i < length;){
int numData = 0;
input.read(reinterpret_cast<char *>(currentWord), sizeof(currentWord));
}
input.close();
output.close();
return 0;
}
让我例外的行是
input.read(reinterpret_cast<char *>(currentWord), sizeof(currentWord));
它在第一次遍历时就这样做了,所以我并没有尝试进一步读取文件。
当我尝试将 currentWord
的值更改为 1 时,出现异常
trying to write to memory 0x0000001
或沿线smth(零的数量可能不正确)
Web 搜索告诉我它与文件为空(事实并非如此)、未找到(也不是这种情况,因为长度获取值)或类型转换 mumbo-jumbo 中的某些内容有关。有什么建议吗?
'currentWord' 为零 (0),当执行 reinterpret_cast<char*>(currentWord)
时,它变为 nullptr
因此当您尝试写入空地址时,您将获得内存写入保护错误。
将其更改为 reinterpret_cast<char*>(¤tWord)
(注意 &
)
您正在使用 current_word
的值,就好像它是一个指针一样。它不是。这就是为什么当 current_word
为零时得到空指针地址,而当 current_word
为 1 时在地址 1 处得到内存异常。使用 ¤t_word
作为 input.read()
的第一个参数.
所以我在这段代码中有这个奇怪的"invalid null pointer"异常(切入问题的核心)
#include <fstream>
#include <iostream>
#include <iomanip>
int main(){
std::ifstream input;
std::ofstream output;
unsigned __int16 currentWord = 0;
output.open("log.txt");
input.open("D:\Work\REC022M0007.asf", std::ios::binary);
input.seekg(0, input.end);
int length = input.tellg();
input.seekg(0, input.beg);
for (int i = 0; i < length;){
int numData = 0;
input.read(reinterpret_cast<char *>(currentWord), sizeof(currentWord));
}
input.close();
output.close();
return 0;
}
让我例外的行是
input.read(reinterpret_cast<char *>(currentWord), sizeof(currentWord));
它在第一次遍历时就这样做了,所以我并没有尝试进一步读取文件。
当我尝试将 currentWord
的值更改为 1 时,出现异常
trying to write to memory 0x0000001
或沿线smth(零的数量可能不正确)
Web 搜索告诉我它与文件为空(事实并非如此)、未找到(也不是这种情况,因为长度获取值)或类型转换 mumbo-jumbo 中的某些内容有关。有什么建议吗?
'currentWord' 为零 (0),当执行 reinterpret_cast<char*>(currentWord)
时,它变为 nullptr
因此当您尝试写入空地址时,您将获得内存写入保护错误。
将其更改为 reinterpret_cast<char*>(¤tWord)
(注意 &
)
您正在使用 current_word
的值,就好像它是一个指针一样。它不是。这就是为什么当 current_word
为零时得到空指针地址,而当 current_word
为 1 时在地址 1 处得到内存异常。使用 ¤t_word
作为 input.read()
的第一个参数.