• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
doyleman77

STL Map and SDL2 Texture segfault

17 posts in this topic

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?

0

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!

0

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

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
0

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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!

0

Share this post


Link to post
Share on other sites

In general I found the [url=http://en.wikipedia.org/wiki/C%2B%2B11]C++11 Wikipedia article[/url] to be a helpful overview, combined with [url=http://en.cppreference.com/w/]cppreference.com[/url] for more details.

2

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
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?
2

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0