c++ - 使用 ifstream 时出现无效空指针错误

标签 c++ nullpointerexception 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;
}

让我异常(exception)的那一行是

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*>(&currentWord) (注意 & )

关于c++ - 使用 ifstream 时出现无效空指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33376774/

相关文章:

c++ - MPI:更改 CMakelist 中的处理器数量

Java 数组 NullPointerException

java - 无法通过空指针异常从索引 i-1 访问数组

c++ - 读取字符串直到行尾

c++ - 如何在 mac 上使用 Ifstream codeblocks?

c++ - 指针或引用

c++ - 识别 C 和 C++ 函数之间逻辑相似性的工具

java - 什么是NullPointerException,我该如何解决?

c++ - 如何将文件的行读入结构数组

c++ - 为 ubuntu 写一个 cygwin makefile