c++ - Project3.exe : 0xC0000005: Access violation reading location 0x00000003 中 0x00C61540 处的未处理异常

标签 c++

每当第二次运行该程序时,我都会收到错误消息。基本上它所做的是将一些信息写入文件,如果文件不存在则创建该文件。然而,当它第二次运行时,它需要读取之前创建的文件,由于某种原因抛出异常,我得到了这个错误:

Project3.exe 中 0x00C61540 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000003。

调试器指向函数getBalance中的第15行是抛出异常的地方。然而,我实际上不止一次调用这个函数,它只是在我第二次调用它时抛出异常。

int getBalance(int lineno){ // Funciton to convert strings in file to ints
    string balance;
//Getting information from the file about locations
int *pointer;
pointer = findNewLines();
static int linenopos[10];

for (int i = 0; i < 11; i++){
    linenopos[i] = *(pointer + i);
}

int balanceInt;

//Opening file
balanceFile.open("E:\\MoneyStuff\\balance.txt", ios::in | ios::out); //Exception is thrown here

//Getting Balances
balanceFile.seekg(linenopos[(lineno - 1)], ios::beg);
getline(balanceFile, balance);

balanceFile.close();

stringstream convert(balance);//Variable to convert string balance to integer balance

//Converting balance string to int
convert >> balanceInt;

//Setting balanceInt to 0 if the file doesn't exist
if (balanceInt < -30000)
    balanceInt = 0;

return balanceInt;
}

编辑:好的,所以我更正了代码中试图访问数组中不存在的元素的部分,但我仍然遇到相同的异常。异常似乎只在我尝试读取以前创建的文件时发生,所以它可能与权限有关吗?

注意:这是我第一次在这里提问,所以如果我需要给你们更多代码或更多信息,请告诉我!谢谢

最佳答案

当您声明一个包含10 个元素 的数组时,这意味着您的索引从09

将循环调整为:

for (int i = 0; i < 10; i++)

尝试访问数组中不存在的元素会导致奇怪的行为,崩溃就是其中之一。

至于由open()引起的异常,捕获它并打印到屏幕上以获得一些线索:

try {
    balanceFile.open("E:\\MoneyStuff\\balance.txt", ios::in | ios::out);
}
catch (const std::exception& e ) {
     std::cout << e.what() << std::endl;
}

关于c++ - Project3.exe : 0xC0000005: Access violation reading location 0x00000003 中 0x00C61540 处的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276565/

相关文章:

c++ - 给定 boost::hana 中的键元组,如何从映射中获取值元组?

c++ - For 循环不按公式输出正确的结果

c++ - setter 导致段错误

c++ - 在 C++ 中找到立方根?

C++ static_cast 运行时开销

c++ - 如果我只给它一个指向我的对象的指针,std::vector 会占用什么内存?

c++ - 位摆弄黑客 : most efficient way to remove one bit every n bits?

c++ - Visual C++ 6.0 链接错误

c++ - 黑/白 PRLock 和 PRRWLock 有什么区别

c++ - boost 正则表达式不匹配?