473,778 Members | 1,901 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

hash_map elements deletion

Hello,

can anybody tell me what's wrong with following example code?

char *k, *v;

k = new char[3];
strcpy(k, "a2");

v = new char[10];
strcpy(v, "987654321" );

mp.insert(std:: pair<const char*, const char*>(k, v));

std::cout << "map size " << mp.size() << std::endl;

// find
TStringMapConst Iterator i = mp.find("a1");
if (i != mp.end())
{
std::cout << " found: " << i->second << std::endl;
}
else
{
std::cout << "not found" << std::endl;
}

// remove
for (TStringMapIter ator j = mp.begin(); j != mp.end(); j++)
{
delete[] (*j).first;
delete[] (*j).second;
}
mp.clear();
std::cout << "deleted" << std::endl;

I'm using gnu c++ compiler and there are few typedefs before this code
to ensure proper comparison and hash computing of const char* in
hash_map

namespace __gnu_cxx
{
template<struct hash<std::strin g>
{
size_t operator()(cons t std::string & __s) const
{ return __stl_hash_stri ng(__s.c_str()) ; }
};

struct tmt_eq_str__
{
bool operator() (const char *a, const char *b) const
{
return !strcmp(a, b);
}
};

}

typedef __gnu_cxx::hash _map<const char*, const char*,
__gnu_cxx::hash <const char *>, __gnu_cxx::tmt_ eq_str__TString Map;
typedef __gnu_cxx::hash _map<const char*, const char*,
__gnu_cxx::hash <const char *>,
__gnu_cxx::tmt_ eq_str__>::cons t_iterator TStringMapConst Iterator;
typedef __gnu_cxx::hash _map<const char*, const char*,
__gnu_cxx::hash <const char *>, __gnu_cxx::tmt_ eq_str__>::iter ator
TStringMapItera tor;

The problem is removal of the elements. Both key and value pairs were
created by new operator. That's why I assumed, that they should be
deleted before callig mp.clear() function.

Problem is that program hangs in infinite loop when deleting elements.
There wasn't such problem when compiling similar code under VC++ 8.0

Thanks in adavance

Mar 7 '07 #1
4 4124
lokki wrote:
Hello,

can anybody tell me what's wrong with following example code?

char *k, *v;

k = new char[3];
strcpy(k, "a2");

v = new char[10];
strcpy(v, "987654321" );

mp.insert(std:: pair<const char*, const char*>(k, v));
What is mp?
>
std::cout << "map size " << mp.size() << std::endl;

// find
TStringMapConst Iterator i = mp.find("a1");
if (i != mp.end())
{
std::cout << " found: " << i->second << std::endl;
}
else
{
std::cout << "not found" << std::endl;
}

// remove
for (TStringMapIter ator j = mp.begin(); j != mp.end(); j++)
{
delete[] (*j).first;
delete[] (*j).second;
}
mp.clear();
Very likely, you corrupted the integrity of the map by deallocating all the
pointers. Does the comparision object / hash function for this map /
unordered_map access the pointees or just the stored pointers? If the
former is the case, the previous run through the list makes it very likely
that you enter undefined behavior.

Suggested fix: don't use char*, use std::string instead.
std::cout << "deleted" << std::endl;

I'm using gnu c++ compiler and there are few typedefs before this code
to ensure proper comparison and hash computing of const char* in
hash_map

namespace __gnu_cxx
{
template<struct hash<std::strin g>
{
size_t operator()(cons t std::string & __s) const
{ return __stl_hash_stri ng(__s.c_str()) ; }
};

struct tmt_eq_str__
{
bool operator() (const char *a, const char *b) const
{
return !strcmp(a, b);
}
};

}

typedef __gnu_cxx::hash _map<const char*, const char*,
__gnu_cxx::hash <const char *>, __gnu_cxx::tmt_ eq_str__TString Map;
typedef __gnu_cxx::hash _map<const char*, const char*,
__gnu_cxx::hash <const char *>,
__gnu_cxx::tmt_ eq_str__>::cons t_iterator TStringMapConst Iterator;
typedef __gnu_cxx::hash _map<const char*, const char*,
__gnu_cxx::hash <const char *>, __gnu_cxx::tmt_ eq_str__>::iter ator
TStringMapItera tor;

The problem is removal of the elements. Both key and value pairs were
created by new operator. That's why I assumed, that they should be
deleted before callig mp.clear() function.

Problem is that program hangs in infinite loop when deleting elements.
There wasn't such problem when compiling similar code under VC++ 8.0

Thanks in adavance
Mar 7 '07 #2
Very likely, you corrupted the integrity of the map by deallocating all the
pointers. Does the comparision object / hash function for this map /
unordered_map access the pointees or just the stored pointers? If the
former is the case, the previous run through the list makes it very likely
that you enter undefined behavior.

Suggested fix: don't use char*, use std::string instead.
I would rather not use std::string because of performance issues in
target application. I tried to analyse that and came to folowing:

- The hash_map in target application will have to hold thousands of
strings.
- The container holds the copy of every object. In case of const
char * it holds only pointer, in case of std::string a complex
object.
- A lot of constructor/copy constructor calls will be neccesary when
inserting std::string to hash_map.
- Data from hash_map will be only read when once inserted. They
should be const, there is no necessity to change them. A very very
fast find is required.
- Almost every external library/ other code in applicaiton is using
const char * for strings.
- After usage, it is required to clear map and to load new data.

I have a previous implementation using std::string and trying to
rebuild it to const char*.
Any advice on safer initialisation/deletion of char pointers in
hash_map?

Thanks a lot anyway

-jk

Mar 7 '07 #3
lokki wrote:
>Very likely, you corrupted the integrity of the map by deallocating all
the pointers. Does the comparision object / hash function for this map /
unordered_ma p access the pointees or just the stored pointers? If the
former is the case, the previous run through the list makes it very
likely that you enter undefined behavior.

Suggested fix: don't use char*, use std::string instead.

I would rather not use std::string because of performance issues in
target application. I tried to analyse that and came to folowing:

- The hash_map in target application will have to hold thousands of
strings.
- The container holds the copy of every object. In case of const
char * it holds only pointer, in case of std::string a complex
object.
- A lot of constructor/copy constructor calls will be neccesary when
inserting std::string to hash_map.
- Data from hash_map will be only read when once inserted. They
should be const, there is no necessity to change them. A very very
fast find is required.
- Almost every external library/ other code in applicaiton is using
const char * for strings.
- After usage, it is required to clear map and to load new data.
Hm, I always found that std::string is just as efficient as char* and
sometimes more efficient (since it stores a length and). Also, I find that
if performance becomes an issue, replacing std::string by some other string
implementation (conforming to the same or similar interface) allows for
better optimization than moving over to char*.

I have a previous implementation using std::string and trying to
rebuild it to const char*.
Any advice on safer initialisation/deletion of char pointers in
hash_map?
You could try this (untested):

void clear_char_ptr_ map ( whatever_type_m p_was & mp ) {
TStringMapItera tor j = mp.begin();
while ( j != mp.end() );
char* dummy_1 = j->first;
char* dummy_2 = j->second;
mp.erase( j++ );
delete [] dummy_1;
delete [] dummy_2;
}
}
It would probably be best if you designed your own map-class that owns the
strings and takes care of all memory management for you.
Best

Kai-Uwe Bux
Mar 7 '07 #4
You could try this (untested):
>
void clear_char_ptr_ map ( whatever_type_m p_was & mp ) {
TStringMapItera tor j = mp.begin();
while ( j != mp.end() );
char* dummy_1 = j->first;
char* dummy_2 = j->second;
mp.erase( j++ );
delete [] dummy_1;
delete [] dummy_2;
}
}
It would probably be best if you designed your own map-class that owns the
strings and takes care of all memory management for you.
Best

Kai-Uwe Bux
Well, I tried and looks it works.

Thank you very much

-jk

Mar 7 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5846
by: Christian Meier | last post by:
Hello, Yes, I know that hash maps aren't in the standard. But I couldn't find any better newsgroup for this post. (or is there an SGI library newsgroup?) I am currently testing the hash_map implementation of SGI. And now I am not sure if it is really true, what I discovered.... Here is my code:
2
1882
by: sam | last post by:
HI, I want to know what the key is in a hash_map object. eg. myhash = "value"; How can I extract the "key_name" from myhash? Thanks Sam
3
843
by: peter_k | last post by:
Please, help me, i'm new to this. I want to do hash_map, where key will be unique structure... struct key { long data; } ....and the value will be unsigned char;
11
2661
by: xz | last post by:
>From the reference of MSDN about hash map: operator Inserts an element into a hash_map with a specified key value. And such example is given: hash_map <int, inthm1; hm1 = 40;
2
4282
by: Amit Bhatia | last post by:
Hi, I am trying to use hash maps from STL on gcc 3.3 as follows: #ifndef NODE_H #define NODE_H #include <ext/hash_map> #include "node_hasher.h" class Node; typedef hash_map<pair<int,int>, Node, Node_HasherLoc_Tree;
1
4474
by: mono12 | last post by:
Hi! I have written code using STL hash_map in c++ and am running into memory issues. I have two kinds of hash_maps: A <int,int> which stores ~5million key-value pairs, and needs to be accessed often to store in memory, its not updated during the program. B <int,hash_map<int,float>> which is also ~5m key-value pairs, but I can read this in parts from the disk. The inner hash_map has about 20 elements. In my program, I read in A and...
5
3908
by: devdude | last post by:
Hi, I have the need to take a snapshot of a hash_map during execution (actually transform it to a vector). This map is a shared resource and therefore must be locked prior to any read/write operations thus I need to minimize the amount of time the map resource is locked. The map is defined as type <string, boost::shared_ptr<myobject>>. My algorithm is as such:
5
3373
by: frankw | last post by:
Hi, I have a hash_map with string as key and an object pointer as value. the object is like class{ public: float a; float b; ...
2
8145
by: marek.vondrak | last post by:
Hi, I am wondering if there are any functional differences between SGI's hash_map and tr1's unordered_map. Can these two containers be interchanged? What would it take to switch from hash_map to unordered_map? Thank you. -Marek
0
9470
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10298
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10127
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8957
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7475
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6723
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4033
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.