STL Map and SDL2 Texture segfault

Started by
16 comments, last by doyleman77 9 years, 9 months ago

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.

Sean Middleditch – Game Systems Engineer – Join my team!

Advertisement

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!

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

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.

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?

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.

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

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

This topic is closed to new replies.

Advertisement