2
votes

I've started using the SFML library for creating a graphical battleships game for university coursework and currently I am creating 4 rectangles to create a border round the window (if there is an easier way to do it please let me know but I want to continue with the 4 rectangle idea)

My issue is I draw the first rectangle to the screen and debug it and it works fine, but then I draw the 2nd one and it throws the following error

Unhandled exception at 0x00656A0E (sfml-graphics-d-2.dll) in Battleships.exe: 0xC0000005: Access violation reading location 0x00000004

Here is my code:

the rectangles are called a and b (sorry for the confusing naming)

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow menu(sf::VideoMode(800, 600), "SFML works!");

    sf::RectangleShape a(sf::Vector2f(800, 20));
    a.setFillColor(sf::Color::White);

    sf::RectangleShape b(sf::Vector2f(20, 600));
    b.setFillColor(sf::Color::White);

    sf::Font font;
    if(!font.loadFromFile("arial.ttf"))
    {
        std::cout << "ERROR: Cannot load font" << std::endl;
    }

    sf::Text text("TEST", font, 80);
    text.setPosition(sf::Vector2f(400/2.0f,300/2.0f));
    text.setColor(sf::Color::White);

    menu.clear();
    menu.draw(a);
    menu.draw(b);
    menu.display();
}
1
If the file isn't found, yes, you display an error. But then your code moves on as if there is no error. - PaulMcKenzie
Are you using visual studio? If so could you please put a break point at the line "sf::Text text("TEST", font, 80);" and check to see if font is equal to anything, it looks like to me you are trying to use a font that hasn't been initialized - Canvas

1 Answers

3
votes
    sf::Font font;
    if(!font.loadFromFile("arial.ttf"))
    {
        std::cout << "ERROR: Cannot load font" << std::endl;
    }

You need to STOP at this point, i.e return from main. Font isn't loaded and then you use it later on, causing a null pointer de-reference.