简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM