3

I am creating an SDL-OpenGL application in D. I am using the Derelict SDL binding to accomplish this.

When I am finished running my application, I want to unload SDL. To do this I run the following function:

public ~this() {
    SDL_GL_DeleteContext(renderContext);
    SDL_DestroyWindow(window);
}

For some reason however, that'll give me a vague segmentation fault (no traces in GDB) and return -11. Can I not destroy SDL in a destructor, do I even have to destroy SDL after use?

My constructor:

window = SDL_CreateWindow("TEST", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP);
if(window == null) {
    string error = to!string(SDL_GetError());
    throw new Exception(error);
}

renderContext = SDL_GL_CreateContext(window);
if(renderContext == null) {
    string error = to!string(SDL_GetError());
    throw new Exception(error);
}
Jeroen
  • 15,257
  • 12
  • 59
  • 102
  • Can you show ctor and some code.- – this Apr 01 '14 at 19:33
  • @self Added my constructor in as well. – Jeroen Apr 01 '14 at 19:52
  • does it change anything if you make them `shared static this` and `shared static ~this`? Without the shared, they are done for each thread and that might cause a problem. – Adam D. Ruppe Apr 02 '14 at 01:35
  • @AdamD.Ruppe Actually I mixed them up with my class destructor. I've my static ones loading Derelict and my class ones are given above. My bad. – Jeroen Apr 02 '14 at 05:21
  • 2
    You also might want to update to [DerelictSDL2](https://github.com/DerelictOrg/DerelictSDL2) when you get the chance, as that's the version that is currently being updated. – cptroot May 06 '14 at 23:58
  • Yes you should be destroying the SDL_Window and you should be calling `SDL_Quit()` as well – TPS Aug 05 '14 at 11:16

1 Answers1

1

Class destructors may run in a different thread than the thread where the class was created. The crash may occur because OpenGL or SDL may not handle cleanup from a different thread properly.

Destructors for heap-allocated (GC-managed) objects are not a good way to perform cleanup, because their invocation is not guaranteed. Instead, move the code to a cleanup function, or use a deterministic way to finalize the object (reference counting, or manual memory management).

Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114