SFML community forums

Help => Graphics => Topic started by: NireL on August 10, 2018, 12:19:34 pm

Title: Access violation writing location
Post by: NireL on August 10, 2018, 12:19:34 pm
Recently I've started working with SFML 2.5. I have the following function that loads a sprite by path and the main method to test it:
#include <SFML/Graphics.hpp>

#include <string>
#include <exception>

sf::Texture loadTexture(const std::string& path)
{
        sf::Texture texture;
        if (!texture.loadFromFile(path))
        {
                throw std::runtime_error("Could not open file: " + path);
        }
        return texture; // This line causes an exception to throw
}

int main()
{
        sf::Texture gameFieldTexture = loadTexture("graphics/field.png");
        return 0;
}
Every time I run the application the commented line above causes an exception to throw with the message:"Unhandled exception at 0x1002DB43 (ig4icd32.dll) in App2_TicTacToe.exe: 0xC0000005: Access violation writing location at 0x00000010".
Everything works fine if I write this code inside the main method. The exception is thrown only when writing a separate function that loads and returns a texture.

Here is the call stack:
(click to show/hide)

My IDE is Visual Studio 2017.

P.S. Sorry if there were some mistakes in the topic. I do not know English well enough.
Title: Re: Access violation writing location
Post by: eXpl0it3r on August 10, 2018, 12:34:10 pm
Are you running the latest Intel GPU driver?
Title: Re: Access violation writing location
Post by: Hapax on August 11, 2018, 04:52:03 pm
The reason you're getting "unhandled exception" is that you aren't catching the exception that you are throwing so it's 'escaping' the program.

Your program needs to know that it's expecting that an exception might be thrown and how to deal with it if it does:
int main()
{
        try
        {
                sf::Texture gameFieldTexture = loadTexture("graphics/field.png");
        }
        catch (std::exception& e)
        {
                std::cerr << e.what() << std::endl;
        }
        return 0;
}

However, that doesn't really explain why the exception is a "writing violation".

Try the above and see what is outputted (from e.what). It might give more information.
Title: Re: Access violation writing location
Post by: achpile on August 17, 2018, 02:32:37 pm
Isn't this because "sf::Texture texture;" declared inside the function and when function returns the value - destructor cleans some internal data?

try better this:

void loadTexture(sf::Texture *texture, const std::string& path)
{
        if (!texture->loadFromFile(path))
        {
                throw std::runtime_error("Could not open file: " + path);
        }
}

int main()
{
        sf::Texture gameFieldTexture;
        loadTexture(&gameFieldTexture, "graphics/field.png");
        return 0;
}