C ++: location of access violation record

Usage: MSVS2012

the code

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 definitely passed an integer from 1 to 4, this is checked before the method is called

difficultyLevel is the string defined in the header file.

The compiler throws the error message "Unhandled Exception" and "Access Violation" ... as soon as it gets into the first if function.

If I remove the if functions and define difficultyLevel as algE just to test the same problem.

If I completely remove difficultyLevel and just open the file as "algE.txt" and "algEAnswers" , then I get the same problem, but in a different memory location, when the code gets into the while loop.

+5
source share
1 answer

Your problem is here:

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

You are not creating an instance of ElemAlg , so you are calling a member function by an uninitialized pointer.

Since the member function you are calling is not virtual, the compiler does not need to perform a run-time search, so the call goes to GetQuiz . However, the this pointer will be garbage (since ea not initialized), so as soon as you access a member variable (e.g. difficultyLevel ), you will have undefined behavior. In your case, undefined behavior leads to an access violation.

Or initialize ea :

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

or, if you do not need to allocate it on the heap, just do:

 ElemAlg ea; ea.GetQuiz(1) 
+13
source

Source: https://habr.com/ru/post/1205104/


All Articles