Mar 9, 2017 at 9:18am UTC
#include <map>
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace std;
struct trnode
{
map<char,trnode*> m;
bool flag;
};
int cnt=0;
map<char,trnode*> :: iterator it;
void recur(trnode *temp)
{
if(temp->flag==true) cnt++;
it = temp->m.begin();
while(it!=temp->m.end())
{
recur((*it).second);
it++;
}
return ;
}
int main(){
int n,k;
char op[7];
char contact[25];
trnode *root = (trnode*)malloc(sizeof(trnode));
root->flag = false;
cin >> n;
for(int a0 = 0; a0 < n; a0++){
cout<<"1011"<<endl;
cin >> op >> contact;
if(strcmp(op,"add")==0)
{
int i=0,l=strlen(contact);
trnode* temp = root,*temp1;
while(i<l)
{
cout<<i<<" "<<l<<endl;
it = temp->m.find(contact[i]);
if(it==temp->m.end())
{
temp1 = (trnode*)malloc(sizeof(trnode));
cout<<sizeof(temp->m)<<endl; //memory allocated for temp->m
temp->m.insert(make_pair(contact[i],temp1));
cout<<"***"<<endl; //this is not being printed as problem with insertin pointer into map above
if(i==l-1)
temp->m[contact[i]]->flag=true;
else temp->m[contact[i]]->flag=false;
}
temp = temp->m[contact[i]];
i++;
cout<<i<<endl;
}
}
else
{
cout<<"1110"<<endl;
trnode* temp = root;
int i=0,l=strlen(contact);k=0;
while(i<l)
{
cout<<"1111"<<endl;
it = temp->m.find(contact[i]);
if(it==temp->m.end())
{
cout<<0<<endl;
k=1;
break;
}
else
{
temp = temp->m[contact[i]];
}
i++;
}
if(k==0){
cnt=0;
recur(temp);
cout<<cnt<<endl;}
}
}
return 0;
}
Last edited on Mar 9, 2017 at 9:23am UTC
Mar 9, 2017 at 10:05am UTC
The problem is this:
temp1 = (trnode*)malloc(sizeof (trnode));
You must use the operator new otherwise the constructor of map will not be called and that leaves the map in an invalid state which causes undefined behavior.