AdamKxZ
AdamKxZ

Reputation: 35

C++: Unhandled exception: std::out_of_range at memory location

Currently learning C++ building a little program that takes in movie names, stores them in a vector and then outputs it based on user input. The problem is I made a function for displaying the movies list. Now every time I run that function I get this error:

Unhandled exception at 0x769DA842 in ConsoleApplication2.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0113F674.

Here's the code:

#include <iostream>
#include <vector>

std::vector <std::string> movieList;
std::vector <int>::iterator it;

void AddMovie(std::string movie)
{
    movieList.push_back(movie);
}

void DeleteMovie(int i)
{
    movieList.erase(movieList.begin() + i - 1);
}

void ShowMovies()
{
    for (int i = 0; movieList.size() > 1; i++)
    {
        std::cout << movieList.at(i) << std::endl;
    }
}

int main()
{

    int i{ 0 };

    movieList.push_back("Inception");
    movieList.push_back("Peter Pan");
    movieList.push_back("Jaws");

    std::cout << "Delete movie: ";
    std::cin >> i;
    DeleteMovie(i);
    ShowMovies();

    
}

The error breaks at line

std::cout << movieList.at(i) << std::endl;

Upvotes: 1

Views: 2809

Answers (1)

Alberto Casas Ortiz
Alberto Casas Ortiz

Reputation: 895

In the for loop, the condition movieList.size() > 1 is always true (if you have more than one movie in the list), so you are incrementing i beyond the size of the list, accessing to memory out of the range of the vector.

This example should work, since the variable i is only used in the body of the loop till it reach movieList.size() - 1 (as @user4581301 commented above, it is increased to movieList.size(), but that last value is not used in the loop body):

void ShowMovies()
{
    for (int i = 0; i < movieList.size(); i++)
    {
        std::cout << movieList.at(i) << std::endl;
    }
}

Upvotes: 1

Related Questions