0

This is C++ on Linux. I'm getting the error during runtime, and I've narrowed down the code to be here, which is a constructor of a custom object. What I do is create a new thread and pass a function to it. In this function, I call the constructor like this:

ColorNinja cn(gameData->difficulty);

gameData is a struct that's also passed to the thread, where difficulty is an int member variable.

I don't fully understand the error or exactly what's causing it. Does anyone have any insight?

Here is the constructor. I can provide more code if necessary.

ColorNinja::ColorNinja(int difficulty) {
    // create the engine that will generate random numbers
    random_device rand;
    mt19937 engine(rand());

    int randomNumber = 0;

    // possible colors that can be present on the randomly-generated game board
    vector<string> possibleColors = {"red", "blue", "yellow", "green"};

    uniform_int_distribution<int> distribution2(0, possibleColors.size());

    // build the game board by choosing and inserting random colors
    for (int i = 0; i < 4; i++) {
        randomNumber = distribution2(engine);
        gameBoard.push_back(possibleColors[randomNumber]);
    }

    // print the game board
    cout << "gameBoard.size(): " << gameBoard.size() << endl;
    for (string s : gameBoard) {
        cout << s << endl;
    }
}
0

1 Answer 1

1

You need to use possibleColors.size()-1 when initializing distribution2:

std::uniform_int_distribution<int> distribution2(0, possibleColors.size()-1);

The two constructor parameters for std::uniform_int_distribution are the minimum and maximum values to be generated. By using possibleColors.size() as the maximum value, you allow the generator to return an index that may be out of bounds of the array. Had you used possibleColors.at(randomNumber), you would have gotten a std::out_of_range error thrown if that actually happened. Using possibleColors[randomNumber] does not perform any bounds checking, so it will happily take an invalid index, and then your code will have undefined behavior. So it is important that you initialize your generator to produce only valid indexes.


On a side note: since possibleColors is a fixed array, consider using std::array instead of std::vector for it:

#include <array>
std::array<string, 4> possibleColors{"red", "blue", "yellow", "green"};
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, that was it! Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.