Jump to content
  • Advertisement
Sign in to follow this  
doyleman77

STL Map and SDL2 Texture segfault

This topic is 1619 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've been to figure out why this keeps breaking for the last 3 days. I'm using a std::map to store all textures in, hopefully, and then just have my link to the images from that map. This works fine on one image; I can load it, store it, and retrieve it to have an entity use it and finally, it gets drawn properly. The minute I add in another texture, however, my game crashes on trying to create an entity that refers to any/either of the textures - GDB has it crashing on a segfault inside the std::map header file, presumably when I'm trying to retrieve the texture.

 

Here's the code in question:

 

Game.cpp

Game::Game()
{
  time(&gameTime);
  timeInfo = localtime(&gameTime);

  gameWindow = SDL_CreateWindow(globals::SCREENTITLE.c_str(),
              SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
              globals::SCREENWIDTH, globals::SCREENHEIGHT, SDL_WINDOW_SHOWN);

  gameRenderer = SDL_CreateRenderer(gameWindow, 0, SDL_RENDERER_ACCELERATED);

  loadTexture("texture.png");
  loadTexture("raindrop.png");
  //gameVector.push_back(&(textureLibrary["raindrop.png"]));

  Entity newEntity(textureLibrary["raindrop.png"]);
  //Entity anotherEntity(&(textureLibrary["raindrop.png"]));
  gameVec.push_back(&(newEntity));
  //gameVec.push_back(&(anotherEntity));

  running = true;
  while(running)
  {
    handleInput(gameInput);
    update();
    draw();
    SDL_Delay(16);
  }
};

Game.cpp

void Game::loadTexture(std::string filename)
{
  SDL_Texture* newTexture = NULL;

  SDL_Surface* loadedSurface = IMG_Load(filename.c_str());
  if(loadedSurface == NULL)
    SDL_Quit();
  /// Set the image invisibility color
  SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0xFF, 0, 0xFF));

  newTexture = SDL_CreateTextureFromSurface(gameRenderer, loadedSurface);

  SDL_FreeSurface(loadedSurface);
  textureLibrary[filename.c_str()] = newTexture;
  return;
};

And finally, my entity constructor - very basic.

Entity::Entity(SDL_Texture* itsTexture)
{
    texture = itsTexture;
    SDL_QueryTexture(itsTexture, NULL, NULL, &texRect->w, &texRect->h);
};

texture is the member of Entity, and is a simple SDL_Texture*.

 

Again; this system worked fine when I had only one image loaded - it wasnt until I had both ["raindrop.png"] and ["texture.png"] that it started segfaulting on the

Entity newEntity(textureLibrary["raindrop.png"]);

bit.

 

Any clues? Don't mind the terrible coding. This is me trying to get a game worked out in a 8wk challenge; and I'm sure it may be sloppy. :(

Share this post


Link to post
Share on other sites
Advertisement

I could be off base here but are you sure the texture is even getting stored in the map?  By the looks of your loadTexture function you are storing a local variable that will be destroyed when the function returns so when you try to access the data it is actually invalid memory because nothing is there.  I could be wrong as I am not sure how SDL_CreateTextureFromSurface operates it might actually malloc memory not sure.  It is just a thought to look into because a segfault is actually caused by accessing invalid (bad) memory.  So the first place I would look is to make sure the texture is actually being stored properly.

Share this post


Link to post
Share on other sites

textureLibrary[filename.c_str()] = newTexture;


That does not look healthy at all. Whatever filename.c_str() returns is only guaranteed to live during that statement. The map should be of type std::map<std::string, whatever> and then you should not call std::string::c_str() here.

Share this post


Link to post
Share on other sites
Entity newEntity(textureLibrary["raindrop.png"]);
gameVec.push_back(&(newEntity));
This could be dangerous. Storing a pointer to a local variable in a member variable is similar to BitMaster highlighted with std::string::c_str(). It might work for the time being given that your game loop is in your Game constructor (which wouldn't be recommended), but could break easily if you're not careful.

It appears you're not quite on top of memory management yet, so you should probably do some more work on that before you continue writing your game. There is nothing more frustrating than trying to understand obscure pointer crashes in C++ - one of my first medium sized projects fell victim to something like this when I was starting out, and I just didn't have the skills to fix it.

I also see a lot of calls to SDL that don't appear to be checking for errors, and the one place you do check for errors you just shutdown SDL without exiting the program. Your program should be full of proper error checking, when something goes wrong at the very least log it to stdout, stderr or a log file, and try to handle it so that your program ends cleanly (e.g return from main() use an exception or at least call std::exit or std::abort). You'll thank yourself a few weeks from now when you make a typo in a texture name and get a nice error message rather than a crash.

Share this post


Link to post
Share on other sites

Ack. Yeah. I should be declaring new on the textures and the entities, and having the map be a pointer to those pointers. Sorry.

 

The map is in fact, a map<std::string, SDL_Texture>. that filename.c_str() is local, but isn't it just calling the characters that make up that string, and storing it into map?

 

IE if I pass "raindrop.png" into loadTexture, it'll pass that into the string, but the string just pumps the characters into the map<string,texture>; and then using map["texture.png"] call it up? I guess I am still new to the STL map - I had to make my own in Data Structures II class at uni, and assumed I could use it somewhat similarly... I've been reading over http://www.cplusplus.com/reference/map/map/ article over and over.

 

What should I be doing instead of filename.c_str() when trying to pass my filename path to the loadTexture function; and then saving it as a key on the map?

Share this post


Link to post
Share on other sites

(Don't mean to double post... I couldn't find an edit button on my post)

 

Also - Yeah, I do intend on going back and doing error checking. I promise, normally I do. I'm just not used to SDL2, and wanted to try to get something up and running quick. That SDL_Quit() call was the last line I added last night before calling it quits, I wanted to see if it even found the image. That part has since been removed. Sorry!

Share this post


Link to post
Share on other sites

The map is in fact, a map<std::string, SDL_Texture>. that filename.c_str() is local, but isn't it just calling the characters that make up that string, and storing it into map?

Ok, the code is fine then, though a little inefficient (requires a new std::string to be constructed). What it appeared to us was that you might have std::map<const char *, SDL_Texture>, which is where the problems would occur.

What should I be doing instead of filename.c_str() when trying to pass my filename path to the loadTexture function; and then saving it as a key on the map?

For storing it in the map, you can just use:
textureLibrary[filename] = newTexture;
The c_str() function is when you need to pass the contents of the string to a C API like SDL.

Yeah, I do intend on going back and doing error checking...

That's OK, just mentioning it.

Share this post


Link to post
Share on other sites

Ack. Yeah. I should be declaring new on the textures and the entities, and having the map be a pointer to those pointers. Sorry.


Do not do this. Never call operator new or delete outside of low-level internal code, like custom data structures (and even then, prefer C++ allocators). Instead, prefer to use std::unique_ptr or std::shared_ptr and std::make_unique or std::make_shared.

The safest thing to use is an owning smart pointer here:
 
// custom deleter needed by unique_ptr to replace use of ::operator delete
struct _TextureDeleter { void operator()(SDL_Texture* tex) const { SDL_FreeTexture(tex); } };

// alias for texture pointers you can use everywhere to save on typing
using TexturePtr = std::unique_ptr<SDL_Texture, _TextureDeleter>;

// a hash map of owned strings to owned textures
std::unordered_map<std::string, TexturePtr> textureLibrary;
That's a map (note it's std::unordered_map since you don't care about sort ordering) of strings to owned pointers to an SDL_Texture that uses SDL_FreeTexture to clean up.

Then add entries efficiently and safely with
 
auto newTexture = TexturePtr{ SDL_CreateTextureFromSurface(gameRenderer, loadedSurface) };

// use std::move to avoid copying large strings, and it's required for the owned pointer newTexture
textureLibrary.insert(std::make_pair(std::move(filename), std::move(newTexture)));
Yeah, modern C++ can be a little more verbose in places, but you get a lot of value out of using the new facilities. Your code is safer, less buggy, easier to analyze, and easier to refactor.

You may find that a std::shared_ptr is a better fit for your resources like textures, but I usually tell people to stick with unique_ptr until it's proven to be the wrong tool for the job. Shared ownership is almost always a sign of lack of thought.

Share this post


Link to post
Share on other sites

// custom deleter needed by unique_ptr to replace use of ::operator delete
struct _TextureDeleter { void operator()(SDL_Texture* tex) const { SDL_FreeTexture(tex); } }; 
// alias for texture pointers you can use everywhere to save on typing
using TexturePtr = std::unique_ptr<SDL_Texture, _TextureDeleter>;

 

I acknowledge that I'm not up to date with '11, yet. It's on my todo list, to get caught up - but this is an 8 week challenge that's already 4 weeks in. I'll try to learn the new smart pointers, eventually.

 

As per the quoted code - I guess I'm not sure what exactly is going on. You're making a structure that overloads the (), takes a texture, and then frees it? and then the last line - using TexturePtr. I'm not sure where TexturePtr is declared, or how it's defined, or what it is really. What is happening when you make a unique pointer with Texture and TextureDeleter?

Edited by doyleman77

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!