繁体   English   中英

使用ifstream时无效的空指针错误

[英]Invalid null pointer error when using ifstream

所以我在这段代码中有一个奇怪的“无效的空指针”异常(切入问题的核心)

#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));

而且它是在第一个过程中进行的,因此,并不是像我正在尝试进一步读取文件那样。

当我尝试将currentWordcurrentWord为1时,出现异常

trying to write to memory 0x0000001

或沿线模糊(零位数可能不正确)

网络搜索告诉我,这与文件为空(不是这种情况),未找到(也不是这种情况,因为长度获取值)或类型转换为mumbo-jumbo有关。 有什么建议么?

'currentWord'为零(0),并且当执行reinterpret_cast<char*>(currentWord) ,它使它成为一个nullptr因此当您尝试写入空地址时,将得到内存写保护错误。

将其更改为reinterpret_cast<char*>(&currentWord) (注意&

您正在使用current_word的值,就好像它是一个指针一样。 不是。 这就是为什么你会得到一个空指针地址时, current_word是零,你在地址1内存异常时current_word是1.使用&current_word作为第一个参数input.read()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM