title: C++: Access violation writing location
body: <p>Using: MSVS2012</p>
  
  <p><strong>Code</strong></p>
  
  <p><em>elemalg.h</em></p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  
  class ElemAlg
  {
  private:
  std::string difficultlyLevel, question, answerToRead;
  std::vector&lt;std::string&gt; questions, answers;
  
  std::vector&lt;std::string&gt; GetQuiz(int);
  };
  </code></pre>
  
  <p><em>elemalg.cpp</em></p>
  
  <pre><code>#include "elemalg.h"
  
  std::vector&lt;std::string&gt; 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;
  }
  </code></pre>
  
  <p><em>MathTutor.cpp</em></p>
  
  <pre><code>#includes etc
  ElemAlg *ea;
  ea-&gt;GetQuiz(1);
  </code></pre>
  
  <p><code>GetQuiz</code> is definitely passed an integer between 1 and 4, this is verified before the method is called</p>
  
  <p><code>difficultyLevel</code> is a string defined in the header file.</p>
  
  <p>The compiler throws an Unhandled exception and Access violation writing location ... as soon as it hits the first <code>if</code> function.</p>
  
  <p>If I remove the <code>if</code> functions and define <code>difficultyLevel</code> as algE just for testing the same problem. </p>
  
  <p>If I remove <code>difficultyLevel</code> entirely and just open the file as <code>"algE.txt"</code> and <code>"algEAnswers"</code> then I get the same problem but at a different memory location once the code hits the while loop.</p>