D
dragoncoder
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() ).
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
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() ).
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