The curse of char*
Whew! Finally I was able to solve the bug I was tring to fix in my game. To explain briefly, I have an std::map<char*, BITMAP*> which is a static member of a class. Now, I have a Manager class which loads resources that somehow looked like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | BITMAP* BitmapManager::addBitmap(char* key, char* fileName) { BITMAP* bitmap = load_bitmap(fileName, NULL); bitmapTable.insert( std::pair<char*, BITMAP*>(key, bitmap) );
return bitmap; }
BITMAP* BitmapManager::getBitmap(char* key) { std::map<char*, BITMAP*>::iterator it = bitmapTable.find(key); BITMAP* bitmap = it->second; return bitmap; } |
As my code goes deeper and deeper and I pass a reference to a BITMAP by calling the BitmapManager's getBitmap function, I somehow encountered a situation when the pointer already became unreacheable and my program would crash when I make a call to BITMAP's(bitmap is a struct) w member which is equivalent to the bitmap width . The call to getBitmap would return NULL or 0.
Thanks to some guy in the allegro.cc forums who advised me to use std::string instead of char*. I don't know the exact reason why this would happen, but the solu worked anyway.
In the end, I didn't use a char* or std::string at all and just used an enum type(implicit integer) for my map key.

The final code look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | BITMAP* BitmapManager::addBitmap(BitmapKeys key, char* fileName) { BITMAP* bitmap = load_bitmap(fileName, NULL); bitmapTable.insert( std::pair<BitmapKeys, BITMAP*>(key, bitmap) );
return bitmap; }
BITMAP* BitmapManager::getBitmap(BitmapKeys key) { std::map<BitmapKeys, BITMAP*>::iterator it = bitmapTable.find(key); BITMAP* bitmap = it->second; return bitmap; } |