Pavan Kumar
Pavan Kumar

Reputation: 77

error using pointers in functions c++

#include <iostream>
using namespace std;
#include <string>
#include <map>

typedef struct node{
    char a;
    map<char , node*> b;
}node;

node a[26] ; 

void add(string s){
    node *prev = &(a[s[0]-'a']);
    int i = 0;
    int len = s.length();
    for(i = 1; i < len; ++i){        
        map<char,node*>::iterator it = ((*prev).b).find(s[i]);
        if(it != ((*prev).b).end()){
            prev = it->second;
        }
        else{
            cout << (*prev).a << endl;
            node pt;
            pt.a = s[i];
            ((*prev).b)[s[i]] = &pt;
            prev = &pt;
        }
    }
}

int main(){
    string s = "helloworld";
    string t = "htllothis";
    int i = 0 ;
    for(i = 0;i < 26;++i){
        a[i].a = 'a'+i;
    }
    add(s);
    add(t);
    return 0;
}

I am trying to implement tire datastructure using map and char but cout<< (*prev).a is printing some other chars. What is the mistake I have done?

Upvotes: 0

Views: 75

Answers (2)

Slava
Slava

Reputation: 44268

First of all (*prev).b is equivalent to prev->b, I do not understand why you use -> for iterator but not for this pointer, it is difficult to read your code.

Main problem that you insert pointer to a local object into map:

       cout << (*prev).a << endl;
       node pt;
       pt.a = s[i];
       ((*prev).b)[s[i]] = &pt;
       prev = &pt;

After leaving this block that pointer becomes invalid and you get random errors. You either should create node by operator new and better have smart pointer in your map, or keep node by value.

Upvotes: 4

aslg
aslg

Reputation: 1974

(...)
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
(...)

In your add function you're creating a local node and passing its address into an entry of the map and then make it the prev node. Once the variable is out of scope it is deleted and your prev node points to an invalid address. So next time you print prevanything could happen as it is Undefined Behaviour.

Upvotes: 0

Related Questions