【问题标题】:C++: Access violation writing locationC++:访问冲突写入位置
【发布时间】:2014-10-20 14:45:28
【问题描述】:

使用:MSVS2012

代码

elemalg.h

#include <vector>
#include <string>
#include <fstream>

class ElemAlg
{
private:
std::string difficultlyLevel, question, answerToRead;
std::vector<std::string> questions, answers;

std::vector<std::string> GetQuiz(int);
};

elemalg.cpp

#include "elemalg.h"

std::vector<std::string> ElemAlg::GetQuiz(int difficulty)
{
if (difficulty == 1) { difficultyLevel = "algE"; }
if (difficulty == 2) { difficultyLevel = "algM"; }  
if (difficulty == 3) { difficultyLevel = "algH"; }
if (difficulty == 4) { difficultyLevel = "algVH"; }

std::ifstream fin(difficultyLevel + ".txt");
while (std::getline(fin, question)) { questions.push_back(question); }
fin.close();

std::ifstream fin2(difficultyLevel + "Answers.txt");
while (std::getline(fin2, answerToRead))    { answers.push_back(answerToRead); }
fin2.close();

return questions;
}

MathTutor.cpp

#includes etc
ElemAlg *ea;
ea->GetQuiz(1);

GetQuiz肯定是传入了一个1到4之间的整数,这个是在方法调用之前验证的

difficultyLevel是头文件中定义的字符串。

编译器在遇到第一个if 函数时立即抛出未处理的异常和访问冲突写入位置。

如果我删除 if 函数并将 difficultyLevel 定义为 algE 只是为了测试相同的问题。

如果我完全删除 difficultyLevel 并以 "algE.txt""algEAnswers" 的身份打开文件,那么一旦代码遇到 while 循环,我就会遇到同样的问题,但在不同的内存位置。

【问题讨论】:

  • difficultyLevel 到底是什么?
  • 参数应该在函数内部使用断言而不是外部进行验证。如果 questions 是一个全局变量,我不知道你为什么要尝试返回它。
  • MCVE 或者它没有发生。
  • 您的 ElemAlg 对象无效。我认为您需要将周围的代码发送给我们。
  • @user3001499 - If I remove the if functions and define difficultyLevel as algE just for testing the same problem 你应该停止删除代码,而是保留原来的错误代码,了解它为什么会给你带来问题并修复它。删除代码可能会隐藏错误,给你一种错误的感觉,即你已经“通过魔法”解决了问题。

标签: c++ access-violation unhandled-exception


【解决方案1】:

你的问题在这里:

ElemAlg *ea;
ea->GetQuiz(1);

您没有创建ElemAlg 的实例,因此您是在未初始化的指针上调用成员函数。

因为您调用的成员函数不是虚拟的,所以编译器不必进行任何运行时查找,这就是调用 GetQuiz 的原因。但是,this 指针将是垃圾(因为ea 未初始化),因此当您访问成员变量(例如difficultyLevel)时,您将有未定义的行为。在您的情况下,未定义的行为会导致访问冲突。

要么初始化ea:

ElemAlg *ea=new ElemAlg;
ea->GetQuiz(1)

或者,如果您不需要在堆上分配它,只需这样做:

ElemAlg ea;
ea.GetQuiz(1)

【讨论】:

  • 非常感谢...我的程序不同,但它帮助我解决了我的问题...我只是使用新关键字更改内存分配语句与语句获得相同错误:MyQueue *newnode = (MyQueue*)malloc(sizeof(MyQueue)); 更改以上声明:MyQueue *newnode = new MyQueue;
猜你喜欢
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多