简体   繁体   中英

Invalid null pointer error when using ifstream

So I have this strange "invalid null pointer" exception in this code (cut down to the core of the problem)

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

The line that gets me exception is

input.read(reinterpret_cast<char *>(currentWord), sizeof(currentWord));

and it do so on the very first go-through, so it's not like I was trying to read file further, than it is.

When I try to change value of currentWord to 1 I get exception like

trying to write to memory 0x0000001

or smth along the lines (number of zeroes may not be correct)

Web search told me it have something to do either with file being empty (which is not the case), not found (not the case either, as length gets value) or something in type casting mumbo-jumbo. Any suggestions?

'currentWord' is ZERO (0) and when reinterpret_cast<char*>(currentWord) is executed it makes it a nullptr so when you try to write to the null address you'll get a memory write protection error.

change it to reinterpret_cast<char*>(&currentWord) (note the & )

You are using the value of current_word as though it were a pointer. It isn't. That's why you get a null pointer address when current_word is zero and you get a memory exception at address 1 when current_word is 1. Use &current_word as the first argument to input.read() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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