473,795 Members | 3,295 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

std::map and insert()

Hello all,

I have the following code. Plesae have a look.

#include <iostream>
#include <string>
#include <map>
#include <cstdlib>

using namespace std;

typedef map<int,string, less<int> > INT2STRING;
INT2STRING::ite rator theIterator;

int main(int argC,char ** argV)
{
INT2STRING * pmap = NULL;
pmap = new INT2STRING;
//pmap = static_cast<INT 2STRING*>(mallo c(sizeof(INT2ST RING)));
for(int i =0;i<10;i++)
{
string buff = "Buffer";
pmap->insert(INT2STR ING::value_type (i,buff));
}

for(int i=0;i<10;i++)
{
theIterator = pmap->find(i);
if(theIterator != pmap->end() ) cout << (*theIterator). second<<
"\n";
else cout << "[err] ";
}
if (pmap != NULL) delete pmap;
//if (pmap != NULL) free (pmap);
}

The code runs perfectly fine. But if I change the new call to malloc()
and delete to free(), I get a segmentation fault ( I am expecting the
problem at the call to insert() ).

Is it necessary to create the map using new only? Can someone please
quote the section of standard which does not allow this to happen.

Best regards

Jun 5 '06 #1
4 3141
dragoncoder wrote:
Hello all,

I have the following code. Plesae have a look.

#include <iostream>
#include <string>
#include <map>
#include <cstdlib>

using namespace std;

typedef map<int,string, less<int> > INT2STRING;
INT2STRING::ite rator theIterator;

int main(int argC,char ** argV)
{
INT2STRING * pmap = NULL;
pmap = new INT2STRING;
//pmap = static_cast<INT 2STRING*>(mallo c(sizeof(INT2ST RING)));
[snip]
The code runs perfectly fine. But if I change the new call to malloc()
and delete to free(), I get a segmentation fault ( I am expecting the
problem at the call to insert() ).


malloc() doesn't call constructors and free() doesn't call destructors.
Don't use them with non POD types.
Jonathan

Jun 5 '06 #2
dragoncoder wrote:
Hello all,

I have the following code. Plesae have a look.

#include <iostream>
#include <string>
#include <map>
#include <cstdlib>

using namespace std;

typedef map<int,string, less<int> > INT2STRING;
INT2STRING::ite rator theIterator;

int main(int argC,char ** argV)
{
INT2STRING * pmap = NULL;
pmap = new INT2STRING;
//pmap = static_cast<INT 2STRING*>(mallo c(sizeof(INT2ST RING)));
for(int i =0;i<10;i++)
{
string buff = "Buffer";
pmap->insert(INT2STR ING::value_type (i,buff));
}

for(int i=0;i<10;i++)
{
theIterator = pmap->find(i);
if(theIterator != pmap->end() ) cout << (*theIterator). second<<
"\n";
else cout << "[err] ";
}
if (pmap != NULL) delete pmap;
//if (pmap != NULL) free (pmap);
}

The code runs perfectly fine. But if I change the new call to malloc()
and delete to free(), I get a segmentation fault ( I am expecting the
problem at the call to insert() ).
Not surprising. malloc simply allocates a memory chunk of a specified
size, it doesn't do anything to the contents of that memory. So you're
basically trying to use a garbage pointer as if it pointed to a
well-formed object. If you insist on using malloc-- and it's unlikely
there's a good reason to do so-- then you must follow it with a call to
placement new to construct an actual object:

new(pmap) INT2STRING;

It is then also your responsibility to call the explicitly call the
destructor before you free the memory.

Is it necessary to create the map using new only? Can someone please
quote the section of standard which does not allow this to happen.


Not only is it not necessary to use new, it's not necessary to
dynamically allocate it at all.

int main ()
{
INT2STRING myMap;

// use myMap as you used pmap-> above
}

This has the obvious advantage of not requiring any intervention on your
part related to memory management. No malloc, no free, no new, and no
delete. Generally, unless you need to dynamically allocate the object
it makes sense to use automatic (i.e., on the stack) objects.

Mark
Jun 5 '06 #3
dragoncoder wrote:
I have the following code. Plesae have a look.

#include <iostream>
#include <string>
#include <map>
#include <cstdlib>

using namespace std;

typedef map<int,string, less<int> > INT2STRING;
INT2STRING::ite rator theIterator;
It's a BAD IDEA(tm) to define things like iterators in the global scope.
int main(int argC,char ** argV)
If you're not going to use 'argC' or 'argV', why declare them?
{
INT2STRING * pmap = NULL;
pmap = new INT2STRING;
Why are the two lines split? Why can't you initialise 'pmap' to the
result of the 'new' expression right where you defined it?
//pmap = static_cast<INT 2STRING*>(mallo c(sizeof(INT2ST RING)));
for(int i =0;i<10;i++)
{
string buff = "Buffer";
pmap->insert(INT2STR ING::value_type (i,buff));
}

for(int i=0;i<10;i++)
{
theIterator = pmap->find(i);
If you drop the global declaration of 'theIterator', you could simply
define it here. Remember, the tighter the scope of an object, the better.
if(theIterator != pmap->end() ) cout << (*theIterator). second<<
"\n";
else cout << "[err] ";
}
if (pmap != NULL) delete pmap;
Deleting a null pointer is a NOP. There is no need to check if it's
NULL or not, just delete.
//if (pmap != NULL) free (pmap);
}

The code runs perfectly fine. But if I change the new call to malloc()
and delete to free(), I get a segmentation fault ( I am expecting the
problem at the call to insert() ).

Is it necessary to create the map using new only? Can someone please
quote the section of standard which does not allow this to happen.


'new' doesn't just allocate memory. It creates the object. 'delete'
doesn't just release the memory, it destroys the object. Objects need
to be created (constructed) before they can be used.

What book are you reading that doesn't explain that?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 5 '06 #4
dragoncoder wrote:
Hello all,

I have the following code. Plesae have a look.

#include <iostream>
#include <string>
#include <map>
#include <cstdlib>

using namespace std;

typedef map<int,string, less<int> > INT2STRING;
INT2STRING::ite rator theIterator;

int main(int argC,char ** argV)
{
INT2STRING * pmap = NULL;
pmap = new INT2STRING;
//pmap = static_cast<INT 2STRING*>(mallo c(sizeof(INT2ST RING)));
for(int i =0;i<10;i++)
{
string buff = "Buffer";
pmap->insert(INT2STR ING::value_type (i,buff));
}

for(int i=0;i<10;i++)
{
theIterator = pmap->find(i);
if(theIterator != pmap->end() ) cout << (*theIterator). second<<
"\n";
else cout << "[err] ";
}
if (pmap != NULL) delete pmap;
//if (pmap != NULL) free (pmap);
}

The code runs perfectly fine. But if I change the new call to malloc()
and delete to free(), I get a segmentation fault ( I am expecting the
problem at the call to insert() ).

Is it necessary to create the map using new only? Can someone please
quote the section of standard which does not allow this to happen.


Out of curiosity, why are you even dynamically allocating the map? Just
declare it local. You don't have to worry about deleteing it then.

When in doubt, if you can avoid new/delete, do so. If you really need
new/delete, then use your favorite smart pointer class.

int main()
{
INT2STRING mymap;

for (int i = 0 ; i < 10; ++i)
mymap.insert(IN T2String::value _type(i, string("Buffer" )));

// etc....
}
Jun 5 '06 #5

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

Similar topics

44
8810
by: jmoy | last post by:
I am a C programmer graduating to C++. As an exercise I wrote a program to count the number of times that different words occur in a text file. Though a hash table might have been a better choice, I chose to use std::map. However, the program runs at less than half the speed of an equivalent program that uses ordinary handcoded binary trees. The result is not changed very much if I replace std::string as the key with a simple string class...
5
426
by: EnTn | last post by:
Hi Everyone... I've been trying to use a std::map to do some storage. Basically, i'm storing double values using a Key Object. The Key object is quite simple and is just a pair of int's (conceptually these are 2d coords). My problem is: I have setup a simple test probgram that populates a map with 9 <key,value> pairs. When I try to query the map using
14
4064
by: Flzw | last post by:
Well I have a map like this : std::map <string, CObject> ObjectList; I have a function like this : CObject* NewObject( char* Name, CArg* Arg) { std::string key = Name; ObjectList = CObject( Name, Arg);
0
1886
by: Erik Arner | last post by:
Hi, let's say I have a std::map<std::string,int> and I want to search the map for all keys that start with "foo". The regexp equivalent is to search for "foo*", or perhaps "^foo*". At present I do this quick'n'dirty by appending a tilde (~) to the query term, since I know it's last in the ascii table and my keys don't include any special characters. So to find everything that starts with "foo" I search the map from...
5
8755
by: Peter Jansson | last post by:
Hello, I have the following code: std::map<int,std::set<std::string> > k; k="1234567890"; k="2345678901"; //... std::set<std::string> myMethod(std::map<int,std::set<std::string> > k) throw(std::runtime_error)
19
6166
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not found anything). Here's the problem, I have two sets of files, the name of a file contains a number which is unique for each set but it's possible (even probable) that two files in different sets have the same numbers. I want to store these...
3
3717
by: Dan Trowbridge | last post by:
Hi everyone, In my attempt to port code from VS 6.0 to VS.NET I had some code break along the way, mostly due to not adhereing closely to the C++ standard. This may be another instance but I can't think of a good fix, or even why it broke. The problem In one of my CFormView derived classes I have a member variable of the type...
10
2480
by: Jim Langston | last post by:
Expected output of program: Key is: 0 String is: Hello Key is: 1 String is: Goodbye Key is: 2 String is: The end Actual output: Key is: 0 String is: The End Key is: 1 String is: Key is: 2 String is:
4
6253
by: Evyn | last post by:
Hi all, I'm starting to fool around with STL and in particular std::map. How do I iterate through one map and insert every pair in another map? I have the following so far: map<double, doublefset1; map<double, doublefset3;
7
10275
by: guido | last post by:
Hi, I'm looking for a container class that can map whole ranges of keys to objects - something like std::map, but not only for individual values for the key, but for whole ranges. Example: I want to be able to tell the container to return object a for every given key between 0 and 10, object c for every key between 11 and 500000 and object c for every key between 500001 and 599999, without having to
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10213
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...
0
10000
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9040
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
7538
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
6780
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();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.