Opening SFML window gives memory read error - c++

I'm trying to open a SFML window, but every time it is launched it says "Access violation reading location: 0xCCCCCCC0." The error is occuring in the init() method. Relevant code:
class AirportGame {
private:
sf::RenderWindow window;
public:
void init();
int run();
/
void AirportGame::init() {
window.create(sf::VideoMode(800, 600), "SFML window");
}
int AirportGame::run() {
init();
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
}
return 0;
}
int main() {
AirportGame* app = new AirportGame();
return app->run();
}
It happens sometime after init, because the actual window is open. There is no mention in the debugger of 0xCCCCCC0.

Fixed it!
Turns out under the C++ pre-processor I set the definition to SFML_STATIC instead of SFML_DYNAMIC

Set window to a
RenderWindow *window;
and create it with
window = new sf::RenderWindow( /*your stuff or default initialize*/ );
and then call
window->create( /*your settings*/ );
if you didn't already initialize it.
From then on just access window using '->' instead of '.'

Related

SFML render window not appearing when running program

When attempting to run a program that is intended to bring forth a render window generated through the SFML library, it will successfully compile but refuse to actually launch a window. After several hours of debugging, I am unable to find where I may have potentially gone wrong in the code, and am now beginning to think it is a problem through my IDE (CLion). Nevertheless, the code used for the render window will be provided.
int main (int argc, const char * argv[])
{
// Create the main window
sf::RenderWindow* window = new sf::RenderWindow(sf::VideoMode(800, 600), "SFML window");
#ifdef SHAPE
sf::Shape s = sf::Shape::Rectangle(0, 0, 100, 100, sf::Color::Blue);
#else
sf::Image img; img.create(100, 100, sf::Color::Blue);
sf::Texture t; t.loadFromImage(img);
sf::Sprite s(t);
#endif
// Start the game loop
while (window->isOpen())
{
// Process events
sf::Event event;
while (window->pollEvent(event))
{
// Close window : exit
if (event.type == sf::Event::Closed)
window->close();
if (event.type == sf::Event::KeyPressed)
if (event.key.code == sf::Keyboard::Escape)
window->close();
else {
delete window;
window = new sf::RenderWindow(sf::VideoMode(800, 600), "SFML window");
}
}
// Clear screen
window->clear();
s.rotate(30.0);
window->draw(s);
// Update the window
window->display();
}
delete window;
return EXIT_SUCCESS;
}
#endif
One of the most common issue with CLion users and launching an application is that they forget to provide the necessary SFML DLLs, so the application never starts but closes with a return value 0xC0000135.
If you launch the executable directly via explorer, you'll get the more well-known message box which tells you which DLL exactly is missing.
The solution is to copy the necessary DLLs next to your executable in the CLion's output directory.

Read Access violation when running gui.get<typename>("") with sfml backend in TGUI

I'm currently trying to use TGUI with SFML as the backend, everything works fine when I had this code
#include <iostream>
#include <TGUI/TGUI.hpp>
int main() {
sf::RenderWindow window{ {800, 600}, "TGUI window with SFML" };
tgui::GuiSFML gui{ window };
gui.loadWidgetsFromFile("menus/startMenu.txt");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
gui.handleEvent(event);
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear();
gui.draw();
window.display();
}
}
However, I then tried to add a line to refer to a button loaded from tgui::Button::Ptr aButton = gui.get<tgui::Button>("a");.
#include <iostream>
#include <TGUI/TGUI.hpp>
int main() {
sf::RenderWindow window{ {800, 600}, "TGUI window with SFML" };
tgui::GuiSFML gui{ window };
gui.loadWidgetsFromFile("menus/startMenu.txt");
tgui::Button::Ptr aButton = gui.get<tgui::Button>("a"); // right here
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
gui.handleEvent(event);
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear();
gui.draw();
window.display();
}
}
and it gives me this error
Exception thrown at 0x7956271B (tgui.dll) in maze 2.exe: 0xC0000005: Access violation reading location 0x000003E4
I'm currently dynamically linking tgui and sfml, using TGUI-0.9 and SFML-2.5.1 with Debug x86 on Visual Studio c++.
The error also tells me it's coming from
template <class T>
typename T::Ptr get(const String& widgetName) const
{
return std::dynamic_pointer_cast<T>(get(widgetName));
}
in Container.hpp in TGUI.
I think that the problem is the dynamic_pointer_cast throwing an error, but I don't know how to fix it. I also don't understand why everything else works except the gui.get<typename>("sometext"); function. Any help?
Edit 1: I've gone ahead and tested with gui.get(), which works perfectly fine. This means that the problem is definitely in the dynamic_pointer_cast, since gui.get<typename>() just calls gui.get() and runs dynamic_pointer_cast on it.
Ok so I just had to restart Visual studio, and it now works perfectly

Why can't I catch this exception? (C++, SFML)

Maybe it's a stupid question but I don't understand why I can catch the exception in the former piece of code, while I can't in the latter.
First piece of code:
int main() {
try {
throw std::logic_error("Error");
sf::RenderWindow window(sf::VideoMode(800, 600), "Test", sf::Style::Default);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
window.display();
}
}
catch(std::logic_error& l){
std::cerr<<l.what()<<std::endl;
exit(42);
}
return 0;
}
Second piece of code:
int main() {
try {
sf::RenderWindow window(sf::VideoMode(800, 600), "Test", sf::Style::Default);
throw std::logic_error("Error");
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
window.display();
}
}
catch(std::logic_error& l){
std::cerr<<l.what()<<std::endl;
exit(42);
}
return 0;
}
At the end I've discovered that the problem regarded how I had linked the SFML library.
I just had to remove -static from target_link_libraries(SFML_Test sfml-system sfml-window sfml-graphics -static) in the CMake file.
Thank you to everyone who has tried to help me.
Probably, because sf::RenderWindow throws exception of another type earlier.
Try catching std::exception, not std::logic_error (it's inherited from std::exception)
Update
Probably your app is crashing during sf::RenderWindow initialization. In this case exception is not generated, but you can try to catch signal.
#include <signal.h>
void fall()
{
int* p = 0x00000000;
*p = 13;
}
void posix_death_signal(int signum)
{
signal(signum, SIG_DFL);
exit(3);
}
int main(int argc, char *argv[])
{
signal(SIGSEGV, posix_death_signal);
fall();
return 0;
}
Or maybe std::abort is called from sf::RenderWindow, so you can try to handle it: https://en.cppreference.com/w/cpp/utility/program/abort
Or std::unexpected. You can try to handle it also
https://en.cppreference.com/w/cpp/error/unexpected
https://en.cppreference.com/w/cpp/error/set_unexpected
std::exit...
Actually I would like to advice attach debugger and see what happens, see how far is running your app before returning
Update 2
Sometimes the root problem is missing DLL which prevents app from starting.

Window not opening in SFML

Basically, I am making a pong clone in c++ and sfml, and I'm using classes, which I have very little knowledge on. The problem is, I'm first of all trying to open the window and clear it in black. The files compile without errors, and run without errors, but the window just doesn't appear.
I believe it has something to do with the constructor, but again, I'm not sure. I looked at all the other questions to see if any answer my question and none of them have given me an answer. Ignore the other header files, they aren't doing anything at the moment.
game.hpp
class Game
{
public:
Game();
void run();
public:
sf::RenderWindow window;
private:
void processEvents();
void update();
void draw();
};
pong.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "game.hpp"
#include "players.hpp"
#include "ball.hpp"
Game::Game() {
sf::RenderWindow window(sf::VideoMode(640, 480), "Game Window", sf::Style::Default);
window.setFramerateLimit(60);
}
void Game::processEvents() {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
}
void Game::draw() {
window.clear(sf::Color::Black);
window.display();
}
void Game::run() {
while (window.isOpen()) {
processEvents();
draw();
}
}
int main(int argc, char const *argv[]) {
Game game;
game.run();
return 0;
}
The window is meant to open and be black, but when the program is run, it runs fine, but the window doesn't pop up. I've been looking at it for a few hours now, have asked some people on a discord server but can't find an answer.
In your Game constructor, you are creating a local window object, that is immediately destroyed when the constructor ends.
Instead of this:
Game::Game() {
sf::RenderWindow window(sf::VideoMode(640, 480), "Game Window", sf::Style::Default);
window.setFramerateLimit(60);
}
Do this:
Game::Game() : window(sf::VideoMode(640, 480), "Game Window", sf::Style::Default)
{
window.setFramerateLimit(60);
}
in order to initialise the window data member with a non-default initialisation.

Why does SFML window not show when window is in a class?

I am trying to create a Screen class for SFML, however for some reason, the application works when using the Xcode example but as soon as I put the window into it's own class, it does not work. Why is this and how would I fix it?
Here is my code (adapted form the example):
Edit:
After reading the comments, I have changed to the following code. This still does not show a screen and the program still quits.
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "ResourcePath.hpp"
class Screen{
public:
sf::RenderWindow window;
Screen(){
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
}
};
int main(int, char const**)
{
Screen* screen = new Screen();
// Set the Icon
sf::Image icon;
if (!icon.loadFromFile(resourcePath() + "icon.png")) {
return EXIT_FAILURE;
}
screen->window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());
// Load a sprite to display
sf::Texture texture;
if (!texture.loadFromFile(resourcePath() + "cute_image.jpg")) {
return EXIT_FAILURE;
}
sf::Sprite sprite(texture);
// Create a graphical text to display
sf::Font font;
if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
return EXIT_FAILURE;
}
sf::Text text("Hello SFML", font, 50);
text.setFillColor(sf::Color::Black);
// Load a music to play
sf::Music music;
if (!music.openFromFile(resourcePath() + "nice_music.ogg")) {
return EXIT_FAILURE;
}
// Play the music
music.play();
// Start the game loop
while (screen->window.isOpen())
{
// Process events
sf::Event event;
while (screen->window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed) {
screen->window.close();
}
// Escape pressed: exit
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
screen->window.close();
}
}
// Clear screen
screen->window.clear();
// Draw the sprite
screen->window.draw(sprite);
// Draw the string
screen->window.draw(text);
// Update the window
screen->window.display();
}
return EXIT_SUCCESS;
}
You have a logic error in your constructor. The way you created it, you leave Screen::window uninitialized, and create another RenderWindow object which becomes inaccessible as soon as execution leaves constructor.
Instead, you should do
class Screen{
public:
sf::RenderWindow window;
Screen():
window(sf::VideoMode(800, 600), "SFML window") {}
};
Everything else should work as expected, unless it does not have any other bugs. If you're curious about the syntax I've used, you can visit this link.
Hard to say. Maybe your accessing a memory address that isn't part of your program? Try using unique pointers and make_unique to define some of your pointers.
For example:
std::unique_ptr<sf::RenderWindow> window;
window = std::make_unique<sf::RenderWindow>(sf::VideoMode(WIDTH, HEIGHT), "PushBlox",sf::Style::Default);
I did make a project using sfml before, so feel free to check out my code here --> https://github.com/FromAlaska/ComputerScience/tree/2017/Projects/Frontier