Jack
Jack

Reputation: 309

function access violation reading location

I have a function which only returns a access violation reading location error when the return statement is within an else but when it is outside of the else no error is turned but I sometimes get the same return value when due to the code I shouldn't. This is the code:

void askUser(){
    std::cout << "Level: ";
    std::cin >> level;

    for (int x = 0; x < 3; x++){
        word = getWord(level);
        std::cout << word << std::endl;
    }
}

std::string getWord(int level){
    int randomNumber = rand() % 3;
    if (usedWords[0].find(line[level - 1][randomNumber]) != usedWords[0].end()){
        getWord(level);
    }
    else{
        usedWords[0].insert(line[level - 1][randomNumber]);
        return line[level - 1][randomNumber];  //returns the access violation error
    }
    //if the return was here no access violation but can return previous return values which shouldn't happen
}

I'm not really sure what is causing the error exactly but I think it's to do with the return statement.

Upvotes: 1

Views: 1188

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57688

The problem is that you are not returning anything when the condition in the if statement is true. The function says you should return a string, but you just come to the end of the function. Undefined behavior.

Upvotes: 3

Related Questions