. Advertisement .
..3..
. Advertisement .
..4..
I get the “access violation writing location c++” error as the title says. How can I fix it so the error goes away? Here is my detail:
#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);
};
#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;
}
#includes etc
ElemAlg *ea;
ea->GetQuiz(1);
When I operated it, I received the error text:
C++: Access violation writing location
I appreciate any help from you.
The cause: I think here is your problem:
Because an instance of
ElemAlg
isn’t created, you are calling a member function on an uninitialized pointer.The compiler won’t have to do any runtime lookup because the member function you’re calling isn’t virtual, which is why the call goes to
GetQuiz
. However, because ea is uninitialized,this
pointer will be garbage, resulting in undefined behavior when you access a member variable (such asdifficultyLevel
). That undefined behavior results in an access violation.Solution: You can solve this error by initializing
ea
:or