Having trouble with pointers in classes - c++

I don't have any trouble when I declare
SDL_Surface *dot = NULL;
globally, but if the SDL_Surface is unique to the class I cant set it to NULL, so thought it would be fine if I declare it in the constructor like
dot = load_image( "dot.bmp" );
but I still get a
Unhandled exception at 0x1002b195 in Uber Mario.exe: 0xC0000005: Access violation reading location 0x0000013c.
on the load_image which returns a SDL_Surface*, sometimes that happened to be because the image was bad or a certain img filetype so i tried another image that does work elsewhere but it still errors like this.
i think im just not using the pointers correctly, even though i studied pointers in school and have read facts on them, for some reason i always have trouble with them. load_image returns a *SDL_Surface so i need to use a pointer...i think.
here is the class:
class Character
{
private:
int yVel, xVel;
int xAcc, yAcc;
int spd, maxV;
int JumpPower;
int FacingRight, FacingLeft;//directing status 0 or 1
bool Flying, onGround;
//Type of particle
SDL_Surface *type;
public:
Shine *myShine;
Animation *walking;
SDL_Surface *dot;
//Offsets
SDL_Rect Rect;
Character();
void handle_input();
void move();
void show();
void togglefly();
void jump();
void whereami();// check and set various characters statuses
};
Character::Character()
{
//Set offsets
Rect.x = 150;
Rect.y = 150;
Rect.w = 20;
Rect.h = 20;
yVel = 0;
xVel = 0;
yAcc = 0;
xAcc = 0;
maxV = 30;
spd = 2;
JumpPower = 40;
Flying = true;
myShine = new Shine(Rect.x, Rect.y);
// walking = new Animation("mario.bmp", 3, 0, 0, Rect.w, Rect.h);
dot = new SDL_Surface();
dot = load_image( "dot.bmp" );
myShine->setpos(Rect);
myShine->setRange(Rect.h*1.5);
}
the load image function:
SDL_Surface *load_image( std::string filename )
{
//The image that's loaded
SDL_Surface* loadedImage = NULL;
//The optimized surface that will be used
SDL_Surface* optimizedImage = NULL;
//Load the image
loadedImage = IMG_Load( filename.c_str() );
//If the image loaded
if( loadedImage != NULL )
{
//Create an optimized surface
optimizedImage = SDL_DisplayFormat( loadedImage ); //EXCEPTION OCCURES HERE
//Free the old surface
SDL_FreeSurface( loadedImage );
//If the surface was optimized
if( optimizedImage != NULL )
{
//Color key surface
SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF ) );
}
}
//Return the optimized surface
return optimizedImage;
init function
bool init()
{
//Initialize all SDL subsystems
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
return false;
}
//Set up the screen
screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
//If there was an error in setting up the screen
if( screen == NULL )
{
return false;
}
//Set the window caption
SDL_WM_SetCaption( "Particle Test", NULL );
//Seed random
srand( SDL_GetTicks() );
//If everything initialized fine
return true;
}

By the way, aren't you leaking resources executing that code:
dot = new SDL_Surface();
dot = load_image( "dot.bmp" );
Doing load_image causes you to loose pointer to SDL_Surface() object hence you cannot delete it later.
Answer to your main issue
Call SDL_Init before using SDL_DisplayFormay and it should work. Citation from SDL documentation.
Newbie hint
You have to call SDL_Init before using the SDL_DisplayFormat function. If you don't, your program will crash with an access violation.

You know, dot is a pointer,and it was allocated dynamiclly.
SDL_Surface *dot=new SDL_Surface();means that you allocate a storage space in heap,and dot index this space.
And,the function load_image(string) return a SDL_Surface type value,that is an object,the return object was assignmented to the pointer dot,then pointer dot changed it's direction,then this makes a memory leak.
You can modify the program by this:
SDL_Surface *dot;
dot = load_image("dot.bmp");
thank you.

Related

I am getting an "Access violation reading location" error when running in release mode - C++

I have tried looking all over the place for an answer but to no avail.
in debugger mode it worked fine but when i put it in release mode it give me this
Unhandled exception at 0x00DC1814 in sdl project.exe: 0xC0000005: Access violation reading location 0x00000000.
i have my debugger and release mode include and library the same, even my subsystems are the same. here is my code, i have shorten it by a bit
SDL_Surface *loadimage();
struct picture
{
int maxframe;
SDL_Surface *surface = NULL;
SDL_Rect rect;
std::string filepath;
};
SDL_Surface *background = NULL;
SDL_Surface *backbuffer = NULL;
SDL_Surface *holder = NULL;
std::vector<picture *> veck;
int main(int argc, char* argu[]){
background = SDL_LoadBMP("pics/bac.bmp");
if (background == NULL){
return false;
}
int height = background->h;
int width = background->w;
init_testprogram();
backbuffer = SDL_SetVideoMode(width, height, 32, SDL_SWSURFACE);
SDL_WM_SetCaption("Yamada's first window", NULL);
//this was here to test if i could format a surface more then once in
//the same format kept in just in case
holder = SDL_DisplayFormat(background);
background = SDL_DisplayFormat(holder);
SDL_FreeSurface(holder);
//this is where i get the error
veck[0]->surface = loadimage();
veck[0]->rect.w = veck[0]->surface->w;
veck[0]->rect.h = veck[0]->surface->h;
//if commented out this is where i get my second error
veck.push_back(new picture);
veck[1]->rect.x = 39;
veck[1]->rect.y = 49;
veck[1]->surface = veck[0]->surface;
veck[1]->rect.w = veck[0]->surface->w;
veck[1]->rect.h = veck[0]->surface->h;
veck[0]->rect.x = 500;
veck[0]->rect.y = 200;
//printing to screan
TTF_Font *font = NULL;
Mix_Chunk *sound = NULL;
picture *picture1;
//if commented out again this is where i get my third error in sound
sound = Mix_LoadWAV("sound/walking in grass.wav");
font = TTF_OpenFont("fonts/CaviarDreams.ttf", 100);
while (programisrunning()){
//do SDL stuff herre
}
SDL_Delay(3000);
SDL_Quit();
TTF_Quit();
Mix_CloseAudio();
int t;
std::cin >> t;
return 0;
}
/////definitions
SDL_Surface *loadimage(){
veck.push_back(new picture);
SDL_Surface* rawimage = NULL;
SDL_Surface* processedimage = NULL;
veck[0]->filepath = "pics/walk 3.png";
rawimage = IMG_Load(veck[0]->filepath.c_str());
if (rawimage == NULL){
errorreport("image 'walk 3.png' failed to load\n");
return false;
}
processedimage = SDL_DisplayFormat(rawimage);
SDL_FreeSurface(rawimage);
if (processedimage == NULL){
errorreport("image 'walk 3.png' failed to process\n");
return false;
}
Uint32 colorkey = SDL_MapRGB(processedimage->format, 255, 255, 255);
SDL_SetColorKey(processedimage, SDL_SRCCOLORKEY, colorkey);
// EDIt
if (processedimage == NULL)
errorreport("ERRRORORROROOR BUT WHY\n");
return processedimage;
}
i know its not in the best way of doing things but this is my test project for doing stuff in sdl. if i comment out the hole veck[0] thing then i get the same error but at further down in veck.pushback() and if i comment out all the vecks then i get the error at sound. i am using visual studio exress 2013 if that helps at all. i don't understand what i am doing wrong.
i did cut out stuff i thought was pointless to add here
You have undefined behavior in veck[0]->surface = loadimage(); since veck[0] won't get an object until loadimage() has executed.
There's no guarantee that loadimage() will be called before veck[0] is evaluated.

C++ SDL2 memory leak? SDL_RenderClear?

I'm using SDL2 on Windows with Code::blocks.
I write this little program. But it cause a memory leak!
The code is very simple. it does only clear and update the screen.
#include <SDL.h>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Event event;
bool quit = false;
void loadSDL();
void closeSDL();
int main( int argc, char* args[] )
{
loadSDL();
while(!quit)
{
while(SDL_PollEvent(&event) != 0)
{
if(event.type == SDL_QUIT)
{
quit = true;
}
}
SDL_RenderClear( renderer );
SDL_RenderPresent( renderer );
}
closeSDL();
return 0;
}
void loadSDL()
{
SDL_Init( SDL_INIT_VIDEO );
window = SDL_CreateWindow( "Test1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF);
}
void closeSDL()
{
SDL_DestroyRenderer( renderer );
SDL_DestroyWindow( window );
window = NULL;
renderer = NULL;
SDL_Quit();
}
I don't know what is wrong...
If I comment this line out
SDL_RenderClear( renderer );
There is no memory leak!
Memory leaks are not the most obvious things to track down. To properly identify a leak, you'll need to use a profiling tool as mentioned in the comments.
The most common reason for what you are seeing is that the OS is free to assign memory to processes before they request it and to delay releasing unused memory. Sometimes this looks like a leak as your process's RAM usage grows in Task Manager. If you wait for a while, it will likely stabilize.
As for a leak specifically in SDL_RenderClear(), it helps to know which renderer you're using. They have different code paths. However, in this case they are quite similar. Here's the GL version from SDL_render_gl.c:
static int
GL_RenderClear(SDL_Renderer * renderer)
{
GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
GL_ActivateRenderer(renderer);
data->glClearColor((GLfloat) renderer->r * inv255f,
(GLfloat) renderer->g * inv255f,
(GLfloat) renderer->b * inv255f,
(GLfloat) renderer->a * inv255f);
data->glClear(GL_COLOR_BUFFER_BIT);
return 0;
}
The only indirect call here is GL_ActivateRenderer(), which does a simple comparison and set. The Direct3D RenderClear() is a little more complicated but does essentially the same thing. It is unlikely that your problem is here.

can i use SDL-1.2.15 with SDL2-image extension?

I have SDL version 1.2.15 install in code block-12.11 when i tries to use it with SDL2-image extension i ran into a certain problem .When i click 'run' a window pop up and vanishes instanly .I followed the instruction of installing the sdl2-image extension from this video http://lazyfoo.net/SDL_tutorials/lesson03/windows/codeblocks/index.php
.Here is what i did
i transfer all the files under lib in sdl2-image extension to lib folder of the codeblock istallation directory and all the files under include i.e-sdl2 folder of sdl2-image extension to include directory of the codeblock and all the files under lib of sdl2-image extension to the exe directory of the program made.
when i run it there is no error but the windows appear and vanishes instanly the code of my program is
#include "SDL/SDL.h"
#include "SDL2/SDL_image.h"
#include <string>
//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
//The surfaces
SDL_Surface *background = NULL;
SDL_Surface *foo = NULL;
SDL_Surface *screen = NULL;
//The event structure
SDL_Event event;
SDL_Surface *load_image( std::string filename )
{
//The image that's loaded
SDL_Surface* loadedImage = NULL;
//The optimized image that will be used
SDL_Surface* optimizedImage = NULL;
//Load the image
loadedImage = IMG_Load( filename.c_str() );
//If the image loaded
if( loadedImage != NULL )
{
//Create an optimized image
optimizedImage = SDL_DisplayFormat( loadedImage );
//Free the old image
SDL_FreeSurface( loadedImage );
//If the image was optimized just fine
if( optimizedImage != NULL )
{
//Map the color key
Uint32 colorkey = SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF );
//Set all pixels of color R 0, G 0xFF, B 0xFF to be transparent
SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorkey );
}
}
//Return the optimized image
return optimizedImage;
}
void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
//Temporary rectangle to hold the offsets
SDL_Rect offset;
//Get the offsets
offset.x = x;
offset.y = y;
//Blit the surface
SDL_BlitSurface( source, NULL, destination, &offset );
}
bool init()
{
//Initialize all SDL subsystems
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
return 1;
}
//Set up the screen
screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
//If there was an error in setting up the screen
if( screen == NULL )
{
return 1;
}
//Set the window caption
SDL_WM_SetCaption( "Foo says \"Hello!\"", NULL );
//If everything initialized fine
return true;
}
bool load_files()
{
//Load the background image
background = load_image( "background.png" );
//If the background didn't load
if( background == NULL )
{
return false;
}
//Load the stick figure
foo = load_image( "foo.png" );
//If the stick figure didn't load
if( foo == NULL )
{
return false;
}
return true;
}
void clean_up()
{
//Free the surfaces
SDL_FreeSurface( background );
SDL_FreeSurface( foo );
//Quit SDL
SDL_Quit();
}
int main( int argc, char* args[] )
{
//Quit flag
bool quit = false;
//Initialize
if( init() == false )
{
return 1;
}
//Load the files
if( load_files() == false )
{
return 1;
}
//Apply the surfaces to the screen
apply_surface( 0, 0, background, screen );
apply_surface( 240, 190, foo, screen );
//Update the screen
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
//While the user hasn't quit
while( quit == false )
{
//While there's events to handle
while( SDL_PollEvent( &event ) )
{
//If the user has Xed out the window
if( event.type == SDL_QUIT )
{
//Quit the program
quit = true;
}
}
}
//Free the surfaces and quit SDL
clean_up();
return 0;
}
is something wrong with the code or installation process or is sdl2-image-2.0.0 extension not compatible with sdl-1.2.15? help
You will either need to use an old version of SDL_Image from here: http://www.libsdl.org/projects/SDL_image/release-1.2.html or you will need to update to SDL2.0.1. I would recommend moving to SDL 2.0.1 because it is a much more modern graphics library.

SDL load bmp problems

I've been following the lazy foo SDL tutorials and have already hit a road block in lesson 2. My code is exactly what he wants, yet i keep getting the same errors whenever i'm trying to blit the following images:
Unhandled exception at 0x68126030 in SDLtest.exe: 0xC0000005: Access violation reading location 0x00000004.
Here is the following code that is constantly producing such errors:
#include "SDL.h"
#include <string>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
SDL_Surface *message = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;
SDL_Surface *load_image(std::string filename)
{
SDL_Surface* loadedImage = NULL;
SDL_Surface* optimizedImage = NULL;
//load the image
loadedImage = SDL_LoadBMP( filename.c_str() );
if (loadedImage != NULL)
{
optimizedImage = SDL_DisplayFormat(loadedImage);
SDL_FreeSurface(loadedImage);
}
return optimizedImage;
}
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination)
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
//blit the surface
SDL_BlitSurface(source, NULL, destination, &offset);
}
int main(int argc, char* args[])
{
if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
{
return 1;
}
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
if (screen = NULL)
{
return 1;
}
SDL_WM_SetCaption("Hello World",NULL);
//loading images
message = load_image("hello.bmp");
background = load_image("background.bmp");
//image blitting
apply_surface(0,0,background,screen);
apply_surface(320,0,background,screen);
apply_surface(0,240,background,screen);
apply_surface(320,240,background,screen);
apply_surface(180,140,message,screen);
if (SDL_Flip(screen) == -1)
{
return 1;
}
SDL_Delay(2000);
SDL_FreeSurface(message);
SDL_FreeSurface(background);
SDL_Quit();
return 0;
}
The error Access violation reading location 0x00000004 is saying that you are dereferencing a pointer whose value is 4, instead of something real.
The easiest way to track this down is to run under a debugger, and see what line causes the problem. Then you can backtrack to figure out where the pointer's value got messed up. Then you may find an error like Bert pointed out.
Replace the line
if(screen = NULL)
with
if(screen == NULL)

Why Is SDL_image not working

I am new to C++ and SDL; I am trying to add a new SDL extension libary using instructions found here: http://www.lazyfoo.net/SDL_tutorials/lesson03/windows/devcpp/index.php
But I get these errors:
3 C:\Documents and Settings\Edmund\My Documents\C++\myprojects\SDL\SDLevent.cpp SDL/SDL_image.h: No such file or directory.
C:\Documents and Settings\Edmund\My Documents\C++\myprojects\SDL\SDLevent.cpp In function `SDL_Surface* load_image(std::string)':
28 C:\Documents and Settings\Edmund\My Documents\C++\myprojects\SDL\SDLevent.cpp `IMG_Load' undeclared (first use this function)
and then a bunch of unqualified ids.
This is my code:
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include <string>
//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
//The surfaces
SDL_Surface *image = NULL;
SDL_Surface *screen = NULL;
//The event structure that will be used
SDL_Event event;
SDL_Surface *load_image( std::string filename )
{
//The image that's loaded
SDL_Surface* loadedImage = NULL;
//The optimized image that will be used
SDL_Surface* optimizedImage = NULL;
//Load the image
loadedImage = IMG_Load( filename.c_str() );
//If the image loaded
if( loadedImage != NULL )
{
//Create an optimized image
optimizedImage = SDL_DisplayFormat( loadedImage );
//Free the old image
SDL_FreeSurface( loadedImage );
}
//Return the optimized image
return optimizedImage;
}
void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
//Temporary rectangle to hold the offsets
SDL_Rect offset;
//Get the offsets
offset.x = x;
offset.y = y;
//Blit the surface
SDL_BlitSurface( source, NULL, destination, &offset );
}
bool init()
{
//Initialize all SDL subsystems
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
return false;
}
//Set up the screen
screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
//If there was an error in setting up the screen
if( screen == NULL )
{
return false;
}
//Set the window caption
SDL_WM_SetCaption( "Event test", NULL );
//If everything initialized fine
return true;
}
bool load_files()
{
//Load the image
image = load_image( "astyle.bmp" );
//If there was an error in loading the image
if( image == NULL )
{
return false;
}
//If everything loaded fine
return true;
}
void clean_up()
{
//Free the image
SDL_FreeSurface( image );
//Quit SDL
SDL_Quit();
}
//Initialize
if( init() == false )
{
return 1;
}
//Load the files
if( load_files() == false )
{
return 1;
}
//Apply the surface to the screen
apply_surface( 0, 0, image, screen );
//Update the screen
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
//While the user hasn't quit
while( quit == false )
{
//While there's an event to handle
while( SDL_PollEvent( &event ) )
{
//If the user has Xed out the window
if( event.type == SDL_QUIT )
{
//Quit the program
quit = true;
}
}
}
//Free the surface and quit SDL
clean_up();
return 0;
}
It is pretty much identical to what is on the tutorial so it should not be a problem with the code. I have followed the Instructions on Lazy foo to the letter, I have put all of the files in the right place and linked to them so i do not know what I am doing wrong.
Your compiler can't find the SDL/SDL_image.h header, that leads to all those 'undeclared' errors.
Maybe you skipped Step 2 in the linked instructions.
Are you sure you have the SDL_Image function at all? What IDE are you using?
If its visual studio make sure you have linked the following:
Also make sure you have downloaded the latest SDL_Image files from http://www.libsdl.org/projects/SDL_image/
Another possible issue is that you havent placed the SDL_Image DLL files in the correct place.
you should use
#include "SDL.h"
#include "SDL_image.h"
and make sure that you have put the sdl include folder in your include directory