Jump to content

  • Log In with Google      Sign In   
  • Create Account

FREE SOFTWARE GIVEAWAY

We have 4 x Pro Licences (valued at $59 each) for 2d modular animation software Spriter to give away in this Thursday's GDNet Direct email newsletter.


Read more in this forum topic or make sure you're signed up (from the right-hand sidebar on the homepage) and read Thursday's newsletter to get in the running!


[SDL] Window instantly closes


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
4 replies to this topic

#1 baosalman   Members   -  Reputation: 104

Like
0Likes
Like

Posted 21 April 2013 - 11:37 AM

Hello everyone. I'm trying to learn SDL and I wrote some code in dev-C++. Everything is fine when I have only the background image but when I try to make a new class which is called Player and try to put a ninja on the screen, it doesn't work. The compiler doesn't give any errors but the window opens up and instantly closes. Ill put my code here.
 
--system.h--
 

#include "SDL/SDL.h"

class System

{

      private:

              int screenWidth, screenHeight;

              bool fullscreen;

              SDL_Surface *buffer;

      public:

             System(){

                 screenWidth=1024;

                 screenHeight=768;

                 }

             System(int W,int H){

                 screenWidth=W;

                 screenHeight=H;

                 }

             

             void Setup();

             SDL_Surface *Screen();

};

 

void System::Setup()

{

     // Initialization

    SDL_Init(SDL_INIT_EVERYTHING);

    // Set window caption

    SDL_WM_SetCaption("BAO SO PRO",NULL);

    bool fullscreen=false;

    

    if (fullscreen==true)

    {

         buffer=SDL_SetVideoMode(screenWidth,screenHeight,32,SDL_SWSURFACE | SDL_FULLSCREEN);

    }

    else

         buffer=SDL_SetVideoMode(screenWidth,screenHeight,32,SDL_SWSURFACE);

}



SDL_Surface * System::Screen()

{

     return buffer;

}

 
 
--player.h--
 
#include "SDL/SDL.h"

class Player {

      private:

              int locx;

              int locy;

              SDL_Surface *playerimage;

      public:

              Player(){

                  locx=0;

                  locy=0;

                  playerimage=NULL;

                  }

              Player(int x,int y){

                  locx=x;

                  locy=y;

                  playerimage=NULL;

                  }

              SDL_Surface *getsurface();

              int getlocx();

              int getlocy();

              void getInput();

              void draw(SDL_Surface *);

              void load(char *);

};

 

int Player::getlocx()

{

    return locx;

}

int Player::getlocy()

{

    return locy;

}

void Player::getInput()

{

    

}

void Player::draw(SDL_Surface *screen)

{

     SDL_Rect *dest;

     dest->x=getlocx();

     dest->y=getlocy();     

     SDL_BlitSurface(playerimage, NULL, screen, NULL);

     delete dest;

}



void Player::load(char *filename)

{

     playerimage=SDL_LoadBMP(filename);

     Uint32 colorkey=SDL_MapRGB(image->format,255,0,255);

     SDL_SetColorKey(image,SDL_SRCCOLORKEY,colorkey);

}



SDL_Surface *Player::getsurface()

{

    return playerimage;

}

 
--main.cpp--
 
#include <iostream>

#include "SDL/SDL.h"

#include "system.h"

#include "player.h"

using namespace std;



int main(int argc, char* args[])

{

    System sys(1024,768);

    sys.Setup();



// Load the image

    Player hero(250,400);

    hero.load("ninja1.bmp");

    SDL_Surface* image;    

    image = SDL_LoadBMP("background.bmp");

 



 



 

 // Main loop

    SDL_Event event;

    while(event.type!=SDL_QUIT)

    {

        // Check for messages

        SDL_PollEvent(&event);

        // Game loop will go here...

        // Apply the image to the display

        

        SDL_BlitSurface(image, NULL, sys.Screen(), NULL);

        hero.draw(sys.Screen());

        

        //Update the display

        SDL_Flip(sys.Screen());



    }



    // Tell the SDL to clean up and shut down

    //SDL_FreeSurface(hero.getsurface());

    SDL_FreeSurface(sys.Screen());

    SDL_Quit();

    

    return 0;    

}


 
Sorry for the long code. I hope someone can help me! If you comment out every hero code, then the program works whereas it pastes the background on the window.
 
Thanks again!

Edited by baosalman, 21 April 2013 - 12:24 PM.


Sponsor:

#2 rip-off   Moderators   -  Reputation: 8762

Like
0Likes
Like

Posted 21 April 2013 - 12:02 PM

Please use the editor tools, or manually type [code] and [/code] tags, to insert your code. As you will see in my post, it creates a nice, colour formatted text field.

 

You have no error checking or handling in your SDL calls. Most SDL calls can return an error, ones that return a pointer may return NULL and most other ones return a negative integer when a problem occurs. At the very least, when SDL returns an error you should log or display the error message returned by SDL_GetError().

 

That said, you are accessing an uninitialised pointer in Player::draw. Consider the following instead:

void Player::draw(SDL_Surface *screen)

{

     SDL_Rect dest = {};

     dest.x = getlocx();

     des.y = getlocy();     

     SDL_BlitSurface(playerimage, NULL, screen, &dest);

}


#3 baosalman   Members   -  Reputation: 104

Like
0Likes
Like

Posted 21 April 2013 - 12:13 PM

Thanks for the hint and the reply! I'll try it right now.

 

Well it didn't work sad.png

 

 

EDIT: Ok I've changed my while loop in the main function. I said while(1) instead of while(event.type!=SDL_QUIT).  Can anyone explain me why this works now?

 

EDIT: Alrighty I've fixed my code! Thanks again.


Edited by baosalman, 21 April 2013 - 01:19 PM.


#4 stitchs   Crossbones+   -  Reputation: 1310

Like
0Likes
Like

Posted 21 April 2013 - 01:53 PM

So has your original code been updated to include the check for SDL_QUIT? As far as I'm aware, while(1) should run the loop continuously.

 

Where you say it works if you comment out the player code is probably due to accessing the non-initialised pointer that rip-off raised. Deleting it without being initially set with 'new' or NULL will probably have an unexpected effect also.

 

Stitchs.



#5 rip-off   Moderators   -  Reputation: 8762

Like
0Likes
Like

Posted 21 April 2013 - 04:35 PM

In the code you posted, you never initialised "event". You then access a member in the loop condition, which is undefined behaviour. Undefined behaviour is C++ lawyer speak for "anything can happen". Here, anything can include:

  • Your program crashes at a point conveniently close to the problematic code
  • Your program writes to arbitrary memory:
    • Crashing sometime later...
    • Continues on with bizarre behaviour (all enemies now have 999 health)
  • Your program appears to work as you intended:
    • Until you try to demo it to your boss/spouse/friend
    • Until someone tries it on a different computer
    • For the time being...
  • ...
  • Ghosts escaping from your computer

Undefined behaviour is often not diagnosed at compile time - that is even if your code compiles cleanly with full errors and warnings, that does not mean that it is correct. Most debug runtimes will try their best to help you detect some types of undefined behaviour, however the very fact that the runtime itself changes how it works in debug versus release mode can sometimes hide such problems.

So, uh, we were talking about your code.

A common fix would be to have the game loop controlled by a boolean variable, and when a SDL_QUIT event is received ensure that the variable becomes false:

bool running = true;
while(running)
{
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        if(event.type == SDL_QUIT)
        {
            running = false;
        }
        else
        {
            // ...
        }
    }
     // ...
}

It may appear that we are still accessing "event" when it is not initialised. However, when SDL_PollEvent() returns true, it will have written some value to event.type. We only access event.type when SDL_PollEvent is true, thus we are not relying on undefined behaviour.

This is one example of why it is so difficult for compilers to help, this extremely common C idiom means that what appears to be a pointer to uninitialised memory is passed into a function which is designed to initialise it, meaning that most compilers will not implement a warning, let alone an error, for such code.


Edited by rip-off, 21 April 2013 - 04:36 PM.
editor eating my code formatting





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS