SFML community forums

Help => Window => Topic started by: Pinco on January 29, 2020, 04:26:38 pm

Title: Switching from debug to release triggers access violation
Post by: Pinco on January 29, 2020, 04:26:38 pm
Hello,
let me preface this by acknowledging that declaring an sf::Window globally is a bad idea and it leads to undefined behavior, however I'd like to know more about this issue. I'm not looking for a solution, I'm trying to learn.
Due to how (poorly) I designed one of my apps I resorted to declaring the Window globally, the compiler (VS2019 IDE) compiles without issues in both Debug and Release mode x86. My problem starts at runtime: it goes smoothly in Release but in Debug it wont open the window throwing an access violation in the sf::Window constructor.

[TLDR] What changes between debug and release? Is it a compiler thing (does the order/schedule of compiling change?)? Is it OS dependent?
Can anyone point me in the right direction?

Note: I'm not looking for a solution to a badly design piece of software, I'm trying to understand the library (and programming in general) on a lower level.

I know it's kind of a weird and useless question so if an admin feels that this post doesn't belong please let me know, I'll be happy to remove it and ask someplace else. Cheers.
Title: Re: Switching from debug to release triggers access violation
Post by: Hapax on January 29, 2020, 09:17:52 pm
My guess would be that in debug, you are shown the problem whereas in release, the problem is invisible. That is, that it is doing something it shouldn't be doing but you don't know about it. This can cause all sorts of problems not least of all is random crashes that might take time to manifest and without any warning.
Title: Re: Switching from debug to release triggers access violation
Post by: eXpl0it3r on January 30, 2020, 08:53:02 am
The reason you can't use global SFML resources like an sf::Window is because SFML internally uses global variables to manage certain cross-cutting states. The initialization and destruction order of global variables is undefined, meaning when you now also use a global variable, C++ does not guarantee that SFML's global variables are initialized before your own sf::Window variable. But since sf::Window depends on SFML being fully initialized, you can run into issues.

Undefined behavior means basically that anything can happen. There's pretty much no point in trying to understand why something works and why something else doesn't. It's undefined, so the behavior can change at random.

One common bit that can cause some issues between debug and release is that in debug memory is oftentimes initialized to 0, where in release the memory will contain anything. This gets noticeable mostly when you have uninitialized variables, not sure if this has anything to do with your situation here.