Search code examples
c++vectorwhile-loopcrashsegmentation-fault

method giving app crashes due to segmentation fault in c++


this simple loop method is unable to run and an error arises "app crashed". when i checked this in an online compiler it gave 'segmentation fault(core dumped)'-

string studies(setMatter ch) {
  string a = "LISTEN CAREFULLY!\n";
  int i = 0;
  while (i <= ch.a.quantity()) {
    a += ch.a.getAns(i);
    i++;
  }
  return a;
}

also see for reference of methods in the above code-

class Answer {
 private:
  vector<string> ch;

 public:
  void setAns(string ans) { ch.push_back(ans); }

  string getAns(int num) { return (ch[num]); }

  int quantity() { return ch.size(); }
};

am i accessing elements out of bond? but i dont know where as i every number starts from 0 in programming


Solution

  • Yes you are.

    while(i<=ch.a.quantity()){
    

    should be

    while(i<ch.a.quantity()){
    

    Valid vector indexes are zero up to the size of the vector minus one. That should be obvious, if the valid indexes started at zero and went to the size of the vector then there would be one more valid index than the size of the vector, which makes no sense.

    Generally you use a for loop for this kind of task

    for (int i = 0; i < ch.a.quantity(); i++) {
        a += ch.a.getAns(i);
    }
    

    It's a little easier to read that way.