Jump to content

  • Log In with Google      Sign In   
  • Create Account

STL Map and SDL2 Texture segfault


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
17 replies to this topic

#1 doyleman77   Members   -  Reputation: 366

Like
3Likes
Like

Posted 06 July 2014 - 06:35 AM

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. :(



Sponsor:

#2 blewisjr   Members   -  Reputation: 622

Like
3Likes
Like

Posted 06 July 2014 - 07:35 AM

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.



#3 BitMaster   Crossbones+   -  Reputation: 4427

Like
4Likes
Like

Posted 06 July 2014 - 07:55 AM

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.

#4 rip-off   Moderators   -  Reputation: 8709

Like
4Likes
Like

Posted 06 July 2014 - 08:28 AM

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.

#5 doyleman77   Members   -  Reputation: 366

Like
0Likes
Like

Posted 06 July 2014 - 08:52 AM

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?



#6 doyleman77   Members   -  Reputation: 366

Like
0Likes
Like

Posted 06 July 2014 - 08:55 AM

(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!



#7 rip-off   Moderators   -  Reputation: 8709

Like
2Likes
Like

Posted 06 July 2014 - 09:15 AM

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.

#8 SeanMiddleditch   Members   -  Reputation: 7133

Like
3Likes
Like

Posted 06 July 2014 - 12:36 PM

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.

#9 SeanMiddleditch   Members   -  Reputation: 7133

Like
2Likes
Like

Posted 06 July 2014 - 12:37 PM

You should use owned pointers like that for SDL_Surface and other similar SDL C types like that, too.

#10 doyleman77   Members   -  Reputation: 366

Like
0Likes
Like

Posted 06 July 2014 - 12:55 PM


// 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, 06 July 2014 - 12:57 PM.


#11 SeanMiddleditch   Members   -  Reputation: 7133

Like
2Likes
Like

Posted 06 July 2014 - 02:31 PM

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?

std::unique_ptr takes as a type-parameter a type that is responsible for deleting the owned pointer. There is a default deleter that uses ::operator delete and looks something like:
 
struct default_deleter {
  void operator()(void* ptr) const {
    delete ptr;
  }
};
The operator() is invoked when it's time to delete the pointer. This is called a "functor" in C++ vernacular. It's a type you can instantiate and then call operator() on as if it were a function, e.g.
 
auto deleter = default_deleter();
deleter(pointer_to_delete);
// or the shorter version; first set of () invokes the constructor and
// creates a temporary instance, second set of () invoked operator() on that instance
defeault_deleter()(pointer_to_delete);
The definition of unique_ptr uses this type parameter as a functor, similar to how std::map uses std::less for its comparison operator. The definition looks something like:
 
template <typename T, typename D = default_deleter> // use default_deleter unless user specifies another type
class unique_ptr : private D { // use inheritance to get the empty base-class optimization
  T* _ptr = nullptr;

public:
  unique_ptr() = default;
  unique_ptr(T* ptr) { reset(ptr); }

  ~unique_ptr() { reset(nullptr); }

  void reset(T* ptr) {
    // note that the following is called even if _ptr is null; the deleter must
    // deal with that, which default_deleter does since delete can be safely
    // called on a null pointer; SDL_Free*() functions also typically are safe
    // to call on a null pointer, too.

    // release our currently owned pointer:
    this->D::operator()(_ptr); }

    // take ownership of the new pointer
    _ptr = ptr;
  }

  // all the other member functions and operators too, of course
};
The use of a type with an overloaded operator() is common in the STL and C++. It's how you can provide a function with enclosed state as a type parameter. Recall that a C++ lambda is just a syntactical short-hand for making a structure like this, e.g.
 
auto lambda = [](int a){ return a * 2; };
struct __lambda_magic_secret_name{ int operator()(int a){ return a * 2; }};
auto lamba = __lambda_magic_secret_name();
That's because the operator() is so crucial to how C++ higher-order functions can be written and composed.

Unfortunately, since the lambda syntax creates an instance of the generated type rather than expanding to the type, it's a bit more difficult to use a lambda for a unique_ptr deleter. Rules about how lambdas can be used make it so we have to resort to a pre-C++11 functor object like _TextureDeleter.

#12 doyleman77   Members   -  Reputation: 366

Like
0Likes
Like

Posted 07 July 2014 - 11:28 AM

I haven't wrapped my mind around lambda's yet, unfortunately. :(

 

Most of c++11 still seems mystified to me; and I can't find a place that breaks down the new features well enough for me to understand.

 

I appreciate and thank you for your explanations, though!



#13 BitMaster   Crossbones+   -  Reputation: 4427

Like
2Likes
Like

Posted 07 July 2014 - 02:08 PM

In general I found the C++11 Wikipedia article to be a helpful overview, combined with cppreference.com for more details.



#14 doyleman77   Members   -  Reputation: 366

Like
0Likes
Like

Posted 07 July 2014 - 07:28 PM

I've read the wiki article before, and while minimal, the code listings arent helping me understand what is going on. Lambdas are by far the worst for me to understand. :-/

 

On a seperate note, regarding my textureLibrary map: would it be that I need to have a getTexture() function that iterates the map, and returns it? Am I not able to simply use textureLibrary["texture.png"] to bring up the appropriate texture? The only problem I could see that causing, at the moment, is that if I use the wrong key, it'd grab a newly made, blank texture. But I don't see why that'd still segfault.

 

I've cleaned up the local variables, and the string bits - and I'm still getting crashes. It's odd, because it seems to work fine on one entity, but not the 2nd. I can directly display the texture using the same key, it only seems to crash when I try to instantiate an Entity with that texture...

 

I apologize if my wording is confusing.



#15 BitMaster   Crossbones+   -  Reputation: 4427

Like
2Likes
Like

Posted 08 July 2014 - 12:27 AM

Run it through a debugger and observe the lines it is crashing on and check the state of everything when that happens. If you don't know how your debugger works yet, now is a perfect time to learn. A simple, reliably to reproduce crash is the textbook example for it.

That said, have you dealt with what rip-off said in post #4?

#16 doyleman77   Members   -  Reputation: 366

Like
0Likes
Like

Posted 08 July 2014 - 07:58 AM

Run it through a debugger and observe the lines it is crashing on and check the state of everything when that happens. If you don't know how your debugger works yet, now is a perfect time to learn. A simple, reliably to reproduce crash is the textbook example for it.

That said, have you dealt with what rip-off said in post #4?

I have. It crashes at line 472 of stl_map.h:

	iterator __i = lower_bound(__k);
	// __i->first is greater than or equivalent to __k.
	if (__i == end() || key_comp()(__k, (*__i).first))
          __i = insert(__i, std::make_pair(std::move(__k), mapped_type()));
	return (*__i).second;
      }

the call stack shows it crashes at the [] operator call of map<>:

 

 

#0 6C78619F    SDL_LogCritical() (C:\Users\name\Dropbox\CardGame\bin\Debug\SDL2.dll:??)
#1 004658B5    std::map<std::string, SDL_Texture*, std::less<std::string>, std::allocator<std::pair<std::string const, SDL_Texture*> > >::operator[](std::string&&) (this=0x4013cd <Entity::Entity(SDL_Texture*&) (c:/program files (x86)/codeblocks/mingw/bin/../lib/gcc/mingw32/4.7.1/include/c++/bits/stl_map.h:472)
#2 00401690    Game::Game(this=0x28fdb0) (C:\Users\name\Dropbox\CardGame\game.cpp:38)
#3 00401F1B    SDL_main(argc=argc@entry=1, args=args@entry=0x340008) (C:\Users\name\Dropbox\CardGame\main.cpp:8)
#4 004027EC    console_main(argc=argc@entry=1, argv=argv@entry=0x340008) (../src/main/windows/SDL_windows_main.c:140)
#5 004029AD    WinMain@16(hInst=0x400000, hPrev=0x0, szCmdLine=0x7b3bf8 "", sw=10) (../src/main/windows/SDL_windows_main.c:177)
#6 0046E23B    main () (??:??)
 

 

I have made my Entities on the heap, and then pushing them onto the Vector<Entity*> GameVec vector - and the segfault occurs there, too - but the app doesn't crash at that point, it just doesn' display the images (where as before, I could do one entity and display it, it'd just crash on 2.)

 

I guess I don't know how to pry open the map<> and test the addresses of what it's pointing too, but for what its worth: it does work if I do a direct SDL_RenderCopy and using the map, rather than the Entity, or if I make a local Texture and assign it a texture from the map, too.


Edited by doyleman77, 08 July 2014 - 08:04 AM.


#17 BitMaster   Crossbones+   -  Reputation: 4427

Like
3Likes
Like

Posted 08 July 2014 - 09:12 AM

If something crashes deep inside the C++ standard library (although a lot of people call it carelessly the 'STL', it is not) you should walk up the stack trace and see what you are doing. Bugs in the standard library happen, but are not common at all. In practically all cases, the error is with you.

You posted a bit limited code (and no one knows how it looks now anyway), so here are two hints:
- if you add pointers to any local objects, you very likely should not do that
- if you add objects to the map, you need to make sure they respect the Rule of Three

Edited by BitMaster, 08 July 2014 - 09:12 AM.


#18 doyleman77   Members   -  Reputation: 366

Like
0Likes
Like

Posted 08 July 2014 - 10:25 AM

The pointers are (I believe) the only local objects now, and are then passed to the map/vector which covers the entire app/game's scope, anyway. The code hasn't changed much, other than declaring new on entities. I also removed the string as a parameter, because somewhere along the line I would have to make a string object to pass upon it.

 

Also, my bad on calling it the stl. I suppose I assumed because it's standard, templated, and a library, that was it's appropriate name. I'm guessing the STL is more of unofficial libraries, where the C++ Libraries are official, and required for most, if not all, C++ compilers...?

 

 

Also, when this segfault happens, Code::Blocks auto opens stl_map.h file - also leading me to believe this is the STL?

 

Anyway, yeah - the code hasn't changed much. I know, I should have all of this loading / game loop outside of the constructor. I'll move it - I've just been occupied with this crashing, so far.

Game::Game()
{
  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("raindrop.png");
  loadTexture("texture.png");

  /// this is me, making sure that the map pulls texture.png. this works.
  SDL_Texture* myTex = textureLibrary["texture.png"];

  Entity* newEntity = new Entity(textureLibrary["raindrop.png"]);
  Entity* anotherEntity = new Entity(textureLibrary["texture.png"]);
  gameVec.push_back(newEntity);
  gameVec.push_back(anotherEntity);

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


void Game::loadTexture(const char filename[])
{
  //SDL_Texture** newTexture = new SDL_Texture*;

  SDL_Surface* loadedSurface = IMG_Load(filename);

  /// Set the image invisibility color
  SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0xFF, 0, 0xFF));

  //*newTexture = SDL_CreateTextureFromSurface(gameRenderer, loadedSurface);

  textureLibrary[filename] = SDL_CreateTextureFromSurface(gameRenderer, loadedSurface);
  SDL_FreeSurface(loadedSurface);
  return;
};
Entity::Entity(SDL_Texture* itsTexture)
{
    texture = itsTexture;
    SDL_QueryTexture(itsTexture, NULL, NULL, &texRect->w, &texRect->h);
};

Here, I initialize SDL, load in some textures (which are then placed into the map/cache), and then I test out by pulling into myTex. Originally, just below that, I did a quick RenderClear, RenderCopy, and RenderPresent to show myTex, and it appeared - in all it's glory.

 

Where as before, when newEntity and anotherEntity were on the stack, rather than the heap, I could _at least_ get newEntity to load it's texture, and display properly, and the anotherEntity would crash; the segfault now happens on newEntity.

 

Following the call stack, the only place other than stl_map.h that maybe is a problem area is the constructor of Game, or maybe of Entity (despite it looking like Entity's constructor isn't on the stack at all, yet).

 

Thanks for the replies.

 

**edit**

 

I've just given up on this...


Edited by doyleman77, 10 July 2014 - 06:56 AM.





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