|
From: K�r�at on 26 May 2008 18:01 Hi, The code below sometimes results access violation at hash_map::erase : char * popItem (int nKey) { char * item = NULL; stdext::hash_map <int, char * >::iterator hmIterator = m_hmItemMap.find (nKey); if (hmIterator != m_hmItemMap.end()) { item = hmIterator->second; m_hmItemMap.erase (nKey); } return item; } I can't find any mistake, what is wrong? Thanks
From: Giovanni Dicanio on 26 May 2008 18:11 "K�r�at" <xx(a)yy.com> ha scritto nel messaggio news:%23JKVVw3vIHA.2064(a)TK2MSFTNGP05.phx.gbl... > The code below sometimes results access violation at hash_map::erase : > > char * popItem (int nKey) > { > char * item = NULL; [...] Could you try using std::string instead of char* ? Giovanni
From: Brian Muth on 26 May 2008 20:43 I'm wondering if the problem lies in code which are not not showing. Where is the char* value portion of the hash_map being allocated? By any chance are you allocated in on the stack?
From: Giovanni Dicanio on 27 May 2008 09:57 "K�r�at" <xx(a)yy.com> ha scritto nel messaggio news:%23JKVVw3vIHA.2064(a)TK2MSFTNGP05.phx.gbl... > The code below sometimes results access violation at hash_map::erase : > > char * popItem (int nKey) > { > char * item = NULL; > > stdext::hash_map <int, char * >::iterator hmIterator = > m_hmItemMap.find (nKey); It seems that you did follow-up neither Brian nor me. However, I still believe that if you use std::string instead of raw char* pointers, you will have no access violation. You may consider the following simple example code, which uses std::string instead of char* (I renamed your popItem() method as Extract()): <code> #include <hash_map> #include <string> class IntToString { public: void Insert( int key, const std::string & value ) { typedef std::pair< int, std::string > IntStringPair; m_map.insert( IntStringPair( key, value ) ); } std::string Extract( int key ) { std::string item; IntToStringMap::iterator it = m_map.find( key ); if ( it != m_map.end() ) { item = it->second; m_map.erase( key ); } else { // Not in map: throw an exception throw std::invalid_argument( "Key not presenet in map." ); } return item; } // ... // ... other members // ... private: typedef stdext::hash_map< int, std::string > IntToStringMap; IntToStringMap m_map; }; </code> Test like this: <code> IntToString map; map.Insert( 1, "January" ); map.Insert( 2, "February" ); map.Insert( 5, "May" ); cout << map.Extract(5) << endl; cout << map.Extract(1) << endl; cout << map.Extract(2) << endl; </code> HTH, Giovanni
|
Pages: 1 Prev: Undefined behaviour? Next: [MSDN documentation error] CEdit::LineLength |