簡體   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