SFML access violation when changing font color

0

I'm having a problem in menu class in my program. When I'm trying to switch menu texts color:

void Menu::moveUp()
{
    if (selectedItemIndex -1 >= 0)
    {
        menuLabel[selectedItemIndex].setColor(false);
        selectedItemIndex--;
        menuLabel[selectedItemIndex].setColor(true);
    }
}

void Menu::moveDown()
{
    if (selectedItemIndex + 1 < NUMBER_OF_MENU_LABELS)
    {
        menuLabel[selectedItemIndex].setColor(false);
        selectedItemIndex++;
        menuLabel[selectedItemIndex].setColor(true);
    }
}

void Menu::update()
{
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    {
        moveUp();
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    {
        moveDown();
    }

}

Exception thrown at 0x51D45960 (sfml-graphics-d-2.dll) in Xan-Man.exe: 0xC0000005: Access violation writing location 0x00000008.

in function

void Writing::setColor(bool color)
{
    if (color)
    {
        text.setFillColor(sf::Color(0, 255, 255)); 
    } 
    else 
    {
        text.setFillColor(sf::Color(255, 255, 255)); 
    }
}

I've tried to implement it with sf::Text not my own class, but It didn't work. Even when I didn't set font I had the same problem.

Somehow when I'll click once down on my keyboard it works, but when I click up It immediately stops and It doesn't switch.

c++
visual-studio
visual-c++
sfml
asked on Stack Overflow Apr 21, 2018 by kubaklamca • edited Jul 6, 2020 by Martijn Pieters

1 Answer

1

Might not be the cause of the error, but if selectedItemIndex is an unsigned integer then the condition if (selectedItemIndex -1 >= 0) could be causing the error if selectedItemIndex is 0 since it will result in the statement being triggered.

Thus, selectedItemIndex will underflow and wrap back to the maximum possible value representable in that type. To which, it'll try to access an element that is out of bounds which might be causing the error.

Try changing the statement to if (selectedItemIndex > 0)

If that doesn't fix it then you'll need to give us more information and or code.

answered on Stack Overflow Apr 21, 2018 by Rabster

User contributions licensed under CC BY-SA 3.0