Re: std::map and insert()
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::iterator theIterator;
int main(int argC,char ** argV)
{
INT2STRING * pmap = NULL;
pmap = new INT2STRING;
//pmap = static_cast<INT2STRING*>(malloc(sizeof(INT2STRING)));
for(int i =0;i<10;i++)
{
string buff = "Buffer";
pmap->insert(INT2STRING::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