segmention fault with pointers

Pages: 12
I received error for bad practice with pointers: that's my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Component {
public:
    Component();
    virtual ~Component();
    void logicFunction();
    void setInputs( Component &);
    char getOutput() const;
protected:
    char  _present_state,_previous_state;
    Component *_x1;
    float _lh,_hl;
private:
};

Component ::Component() {
    //ctor
}

Component ::~Component() {
    //dtor
}

void Component ::setInputs( Component &a){
    *_x1=a;
}

char Component ::getOutput() const {
    return _present_state;
}

class And : public Component{
public:
    And();
    virtual ~And();
    void logicFunction();
    void setInputs( Component&,  Component&);
protected:

private:
    Component *_x2;
} ;

And ::And(){
    _x1= nullptr;
    _x2= nullptr;
}

And :: ~And() {
    //dtor
}

void And::logicFunction() {
    _previous_state=_present_state;
    if((_x1->getOutput()=='x')||(_x2->getOutput()=='x')) _present_state='x';
    else _present_state=char(bool(_x1->getOutput())&&bool(_x2->getOutput()));
}

void And::setInputs( Component &a,  Component &b) {
    *_x1=a;
    *_x2=b;
}

class ConstantComponent : public Component{
public:
    ConstantComponent();
    virtual ~ConstantComponent();
    void setState(bool&);
    void logicFunction();
protected:

private:

};

ConstantComponent :: ConstantComponent() {
    _x1= nullptr;
}


ConstantComponent ::~ConstantComponent() {
    //dtor
}


void ConstantComponent :: setState(bool &input) {
    _present_state=input;
}
moreover:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#define dict_lenght 7
struct element{
    string name;
    ConstantComponent *data;
};

class Circuit
{
    friend class Component;
public:
    Circuit();
    virtual ~Circuit();
    void setFileName();
    void openFile() ;
    void closeFile() ;
    bool setInputs();
    bool buildGraph();
    bool getWord(string&);
    void makeVectors(int& );
    bool doOp(int&);
    int checkOperator(string&);
    int checkInput(string&);
    bool assign(Component* );
    void tree(int, stack<Component*>);
    //component addComponent();
protected:

private:
    vector <element> _input_vector;
    vector <element> _output_vector;

    string _dictionary[dict_lenght]={"clk","input","output","assign","instance","endmodule", "ffx"};
    string _gate[dict_lenght]={"not","and","or", "xor","nand","nor","xnor"};
    string _file_name;
    ifstream _my_file;
    bool _clock,_sequenziale;
};

void Circuit :: makeVectors(int& i){
    char *pch;
    char buffer[200];
    string line;
    int j=0;
    getline(_my_file,line);
    strcpy(buffer,line.c_str());
    pch = strtok(buffer, ", ");
    while(pch != nullptr){
        if(i==1) {
            j = _input_vector.size();
            _input_vector.push_back( { pch, new ConstantComponent } );
        }else{
            j= _output_vector.size();
            _output_vector.push_back( { pch, new ConstantComponent } );
        }
        pch = strtok(nullptr, ",");
    }
}

bool Circuit :: assign(Component *head){
    char *pch;
    char buffer[200];
    string line;
    int i=0,address;
    Component* cpPtr;
    cpPtr= nullptr;
    bool Aflag= false;
    queue<string> output_queue;
    stack<string> operator_stack;
    stack<Component*> address_stack;
    getline(_my_file,line);
    strcpy(buffer,line.c_str());
    pch = strtok(buffer, " ");
    while(pch != nullptr) {
        //shunting-yard
        if (pch=="(") {
            operator_stack.push(pch);
            break;
        }
        if (pch==")"){
            while(operator_stack.top()!="("){
                output_queue.push(operator_stack.top());
                operator_stack.pop();
            }
            if (operator_stack.empty()){
                cout<<"errore: mismatching '(' in assign";
                return false;
            }
            operator_stack.pop();
            break;
        }
        i=0;
        while (i<_input_vector.size()){
            if (pch==_input_vector[i].name){
                output_queue.push(pch);
                break;
            }
            i++;
        }
        i=0;
        while(i<dict_lenght){
            if (pch==_gate[i]) {
                while ((!operator_stack.empty() /*||*/ /*operator_stack.top().c_str() == "not"*/) && (operator_stack.top().c_str() != "(")) {
                    output_queue.push(operator_stack.top());
                    operator_stack.pop();
                }
                operator_stack.push(pch);
                break;
            }
            i++;
        }

        pch = strtok(nullptr, " ");
    }
    while (!operator_stack.empty()){
        output_queue.push(operator_stack.top());
        operator_stack.pop();
    }
    
    while(!output_queue.empty()){
        if(output_queue.size()==1){
             tree(checkOperator(output_queue.front()), address_stack);
         }
        if (checkOperator(output_queue.front())>=0){  
            tree(checkOperator(output_queue.front()), address_stack);
            if (output_queue.size()==1){
                head=address_stack.top();
            }
            output_queue.pop();
        }
        address = checkInput(output_queue.front());
        if (address>=0){
            cpPtr=_input_vector[address].data;
            address_stack.push(cpPtr);
            output_queue.pop();
        }
    }
}

int Circuit :: checkOperator(string& operatore){
    // if
    for (int i=0;i<dict_lenght;i++){
        if (_gate[i]==operatore) {
            return i;
        }
    }
    return -1;
}

int Circuit :: checkInput(string &word){
    for (int i=0; i<dict_lenght; i++){
        if (_input_vector[i].name==word){
            return i;
        }
    }
    return -1;
}

void Circuit :: tree(int address, stack<Component*> stack) { //and","or", "xor","nand","nor","xnor"};
    Component* temp= nullptr;
    Not *pNot = new Not;
    And *pAnd = new And;
    Or *pOr = new Or ;
    Xor *pXor = new Xor;
    Nand *pNand = new Nand;
    Nor *pNor = new Nor;
    Xnor *pXnor = new Xnor;
    switch (address) {
        case 0:
            temp=stack.top();
            pNot->setInputs(*temp);
            stack.pop();
            stack.push(pNot);
            break;
        case 1:
            temp=stack.top();
            stack.pop();
            pAnd->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pAnd);
            break;
        case 2:
            temp=stack.top();
            stack.pop();
            pOr->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pOr);
            break;
        case 3:
            temp=stack.top();
            stack.pop();
            pXor->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pXor);
            break;
        case 4:
            
            temp=stack.top();
            stack.pop();
            pNand->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pNand);
            break;
        case 5:
            
            temp=stack.top();
            stack.pop();
            pNor->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pNor);
            break;
        case 6:
            
            temp=stack.top();
            stack.pop();
            pXnor->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pXnor);
            break;
        default:break;
    }
}


Suppose function makeVector is right and so _input_vector has elements, I riceiver error when I try to allocate a And gate:
 
pAnd->setInputs(*stack.top(), *temp);
Sorry for all the code, it doesn't work and I'm desperated
help us to help you.

what is the exact error text?

pAnd->setInputs(*stack.top(), *temp);

what are the expected and actual values of the above (for pointers 'valid' vs null is sufficient)?
is pAnd valid? if it is, is stack.top() valid? If so, is temp valid?
If all those are Ok, then dig into the function and repeat the process, what is going on inside that can break? its tiny, but it has x1 = a ... is x1 valid? is a valid? What did that assignment operator do, now you have to go through that ...

If you are going to insist on using pointers, you need to learn to debug them. That means keeping track of each one as you code... because letting just one go astray will put you in a big mess.
Last edited on
Process finished with exit code -1073741819 (0xC0000005)

in debug:

Signal =-var-create: unable to create variable object
signal=SIGSEGV (Segmentation fault).

Jonnin sorry, I don't understand what you are meaning.
I know I'm not very good with pointers, but please help me. I have to finish this project in a few days and I find lots of error.. help me, I'm desperated.
I can't graduate if I don't do this.

Where are your #includes?

Too many warnings to even bother with. I suggest you turn up your compiler warning levels and fix all warnings before you go any further.

For example just a small sampling:
main.cpp|1|warning: ‘class Component’ has pointer data members [-Weffc++]|
main.cpp|1|warning: but does not override ‘Component(const Component&)’ [-Weffc++]|
main.cpp|1|warning: or ‘operator=(const Component&)’ [-Weffc++]|
main.cpp||In constructor ‘Component::Component()’:|
main.cpp|15|warning: ‘Component::_present_state’ should be initialized in the member initialization list [-Weffc++]|
main.cpp|15|warning: ‘Component::_previous_state’ should be initialized in the member initialization list [-Weffc++]|
main.cpp|15|warning: ‘Component::_x1’ should be initialized in the member initialization list [-Weffc++]|
main.cpp|15|warning: ‘Component::_lh’ should be initialized in the member initialization list [-Weffc++]|
main.cpp|15|warning: ‘Component::_hl’ should be initialized in the member initialization list [-Weffc++]|
main.cpp|31|warning: ‘class And’ has pointer data members [-Weffc++]|
main.cpp|31|warning: but does not override ‘And(const And&)’ [-Weffc++]|
main.cpp|31|warning: or ‘operator=(const And&)’ [-Weffc++]|
main.cpp||In constructor ‘And::And()’:|
main.cpp|43|warning: ‘And::_x2’ should be initialized in the member initialization list [-Weffc++]|
main.cpp||In member function ‘void Circuit::makeVectors(int&)’:|
main.cpp|141|warning: variable ‘j’ set but not used [-Wunused-but-set-variable]|
main.cpp||In member function ‘bool Circuit::assign(Component*)’:|
main.cpp|173|warning: comparison with string literal results in unspecified behavior [-Waddress]|
main.cpp|177|warning: comparison with string literal results in unspecified behavior [-Waddress]|
main.cpp|190|warning: comparison between signed and unsigned integer expressions [-Wsign-compare]|
main.cpp|200|warning: comparison with string literal results in unspecified behavior [-Waddress]|
main.cpp|164|warning: unused variable ‘Aflag’ [-Wunused-variable]|
main.cpp|157|warning: parameter ‘head’ set but not used [-Wunused-but-set-parameter]|


You have pointer member variables so you need to have a constructor, destructor , copy constructor, and assignment operators that do something or are at least "deleted" to prevent errant copying and assignments.
main.cpp|173|warning: comparison with string literal results in unspecified behavior [-Waddress]|
main.cpp|177|warning: comparison with string literal results in unspecified behavior [-Waddress]|

These are very telling, do you realize how bad unspecified/undefined behavior really is?

Perhaps you would be better off abandoning C-strings and stick with C++ strings?

I suggest you consider using stringstreams and std::string.find() methods instead of the strtok() if at all possible.

Lastly, for now, many of your functions are doing too much, IMO, and should be simplified. And do you realize that in C++ not everything should be part of a class, it is perfectly acceptable to have non-member functions and variables?


ok, i give you all the code
component.h :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdlib.h>
#include <vector>
#include <string>
#include <fstream>
#include <string.h>
#include <cctype>
using namespace std;

#ifndef ALGORITMI2_COMPONENT_H
#define ALGORITMI2_COMPONENT_H


 //template perché stato può essere X
class Component {
public:
    Component();
    virtual ~Component();
    void logicFunction();
    void setInputs( Component &);
    char getOutput() const;
    //void setState(bool&);//serve per vettore input: essendo vettore component, serve il metodo che viene implementato in constant component
protected:
    char  _present_state,_previous_state;
    Component *_x1;
    float _lh,_hl;// consumo da low a high e da high a low
private:
};


class Not : public Component{
public:
    Not();
    virtual ~Not();
    void logicFunction();

protected:

private:
} ;

class And : public Component{
public:
    And();
    virtual ~And();
    void logicFunction();
    void setInputs( Component&,  Component&);
protected:

private:
    Component *_x2;
} ;

class Nand : public Component{
public:
    Nand();
    virtual ~Nand();
    void logicFunction();
    void setInputs( Component&,  Component&);
protected:

private:
    Component *_x2;
} ;

class Or : public Component{
public:
    Or();
    virtual ~Or();
    void logicFunction();
    void setInputs( Component&,  Component&);
protected:

private:
    Component *_x2;
} ;

class Nor : public Component{
public:
    Nor();
    virtual ~Nor();
    void logicFunction();
    void setInputs( Component&,  Component&);
protected:

private:
    Component *_x2;
} ;

class Xor : public Component{
public:
    Xor();
    virtual ~Xor();
    void logicFunction();
    void setInputs( Component&,  Component&);
protected:

private:
    Component *_x2;
} ;

class Xnor : public Component{
public:
    Xnor();
    virtual ~Xnor();
    void logicFunction();
    void setInputs( Component&,  Component&);
protected:

private:
    Component *_x2;
} ;

class FlipFlop : public Component{
public:
    FlipFlop();
    virtual ~FlipFlop();
    void logicFunction();
    void setClock(bool&);
protected:

private:
    bool _clock;
} ;

class ConstantComponent : public Component{
public:
    ConstantComponent();
    virtual ~ConstantComponent();
    void setState(bool&);
    void logicFunction();
protected:

private:

};

component.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#include "Component.h"
Component ::Component() {
    //ctor
}

Component ::~Component() {
    //dtor
}

void Component ::setInputs( Component &a){
    *_x1=a;
}

char Component ::getOutput() const {
    return _present_state;
}


Not :: Not() {
    _x1= nullptr;
}

Not :: ~Not() {
}

void Not ::logicFunction() {
    _previous_state=_present_state;
    if (_x1->getOutput()=='x') _present_state='x';
    else _present_state=char(!bool(_x1->getOutput()));
}


And ::And(){
    _x1= nullptr;
    _x2= nullptr;
}

And :: ~And() {
    //dtor
}

void And::logicFunction() {
    _previous_state=_present_state;
    if((_x1->getOutput()=='x')||(_x2->getOutput()=='x')) _present_state='x';
    else _present_state=char(bool(_x1->getOutput())&&bool(_x2->getOutput()));
}

void And::setInputs( Component &a,  Component &b) {
    *_x1=a;
    *_x2=b;
}


Nand ::Nand(){
    _x1= nullptr;
    _x2= nullptr;
}

Nand :: ~Nand() {
    //dtor
}

void Nand::logicFunction() {
    _previous_state=_present_state;
    if((_x1->getOutput()=='x')||(_x2->getOutput()=='x')) _present_state='x';
    else _present_state=char(!(bool(_x1->getOutput())&&bool(_x2->getOutput())));
}

void Nand::setInputs( Component &a,  Component &b) {
    *_x1=a;
    *_x2=b;
}


Or ::Or(){
    _x1= nullptr;
    _x2= nullptr;
}

Or :: ~Or() {
    //dtor
}


void Or::logicFunction() {
    _previous_state=_present_state;
    if((_x1->getOutput()=='x')||(_x2->getOutput()=='x')) _present_state='x';
    else _present_state=char(bool(_x1->getOutput())||bool(_x2->getOutput()));
}

void Or::setInputs( Component &a,  Component &b) {
    *_x1=a;
    *_x2=b;
}


Nor ::Nor(){
    _x1= nullptr;
    _x2= nullptr;
}

Nor :: ~Nor() {
    //dtor
}


void Nor::logicFunction() {
    _previous_state=_present_state;
    if((_x1->getOutput()=='x')||(_x2->getOutput()=='x')) _present_state='x';
    else _present_state=char(bool(!(_x1->getOutput())||bool(_x2->getOutput())));
}

void Nor::setInputs( Component &a,  Component &b) {
    *_x1=a;
    *_x2=b;
}


Xor ::Xor(){
    _x1= nullptr;
    _x2= nullptr;
}

Xor :: ~Xor() {
    //dtor
}

void Xor::logicFunction() {
    _previous_state=_present_state;
    if((_x1->getOutput()=='x')||(_x2->getOutput()=='x')) _present_state='x';
    else _present_state=char(bool(_x1->getOutput())^bool(_x2->getOutput()));
}

void Xor::setInputs( Component &a,  Component &b) {
    *_x1=a;
    *_x2=b;
}


Xnor ::Xnor(){
    _x1= nullptr;
    _x2= nullptr;
}

Xnor :: ~Xnor() {
    //dtor
}

void Xnor::logicFunction() {
    _previous_state=_present_state;
    if((_x1->getOutput()=='x')||(_x2->getOutput()=='x')) _present_state='x';
    else _present_state=char(!(bool(_x1->getOutput())^bool(_x2->getOutput())));
}

void Xnor::setInputs( Component &a,  Component &b) {
    *_x1=a;
    *_x2=b;
}


FlipFlop ::FlipFlop() {
    _present_state='x';
    _x1= nullptr;
}

FlipFlop :: ~FlipFlop() {
    //dtor
}


void FlipFlop :: logicFunction() {
    if (_clock==true){
        _previous_state=_present_state;
        if(_x1->getOutput()=='x') _present_state='x';
        else _present_state=_x1->getOutput();
    }
}


void FlipFlop::setClock(bool &clock) {
    _clock = clock;
}


ConstantComponent :: ConstantComponent() {
    _x1= nullptr;
}


ConstantComponent ::~ConstantComponent() {
    //dtor
}


void ConstantComponent :: setState(bool &input) {
    _present_state=input;
}


#endif //ALGORITMI2_COMPONENT_H 
Last edited on
circuit.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "Component.h"
#include <stdlib.h>
#include <vector>
#include <string>
#include <fstream>
#include <string.h>
#include <cctype>
#include <queue>
#include <stack>
#include <iostream>
using namespace std;
#ifndef ALGORITMI2_CIRCUIT_H
#define ALGORITMI2_CIRCUIT_H


#define dict_lenght 7
struct element{
    string name;
    ConstantComponent *data;//puntatore perché component è classe astratta
};

class Circuit
{
    friend class Component;//ha accesso ai metodi di component
public:
    Circuit();
    virtual ~Circuit();
    void setFileName();
    void openFile() ;
    void closeFile() ;
    bool setInputs();
    bool buildGraph();
    bool getWord(string&);
    void makeVectors(int& );
    bool doOp(int&);
    int checkOperator(string&);
    int checkInput(string&);
    bool assign(Component* );
    void tree(int, stack<Component*>);
    //component addComponent();
protected:

private:
    vector <element> _input_vector;
    vector <element> _output_vector;

    string _dictionary[dict_lenght]={"clk","input","output","assign","instance","endmodule", "ffx"};
    string _gate[dict_lenght]={"not","and","or", "xor","nand","nor","xnor"};
    string _file_name;
    ifstream _my_file;
    bool _clock,_sequenziale;
};


#endif //ALGORITMI2_CIRCUIT_H 
circuit.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#include "Circuit.h"

Circuit::Circuit()
{
    setFileName();
    openFile();
    _sequenziale=false;
    buildGraph();
    //ctor
}

Circuit::~Circuit()
{
    closeFile();
    //dtor
}


bool Circuit :: setInputs() {
    string input_file_name;
    ifstream input_file;
    cout<<"inserire nome file contente lista input: ";
    cin>>input_file_name;
    string line;
    bool state;
    int i=0;
    input_file.open(input_file_name.c_str(),ios::in);
    if (!input_file.is_open()) cout<<"error: file input non trovato";
    else{
        while (getline(input_file,line)){//leggi una riga, assegna ogni carattere della riga a un input e fai simulazioni. poi leggi altra riga. controlla se ci sono errori
            while(i<_input_vector.size()) {
                if (line[i] == '0' || line[i] == '1') {
                    state = bool(line[i]);
                    _input_vector[i].data->setState(state);
                    i++;
                } else {
                    cout << "errore: hai inserito un carattere non valido; inserire solo '0' o '1'";
                    return false;
                }
            }
            //DoSimulation();
            i=0;
        }
    }
    i=0;
    while (i<_output_vector.size()){
        cout<<_output_vector[i].data->getOutput();
        i++;
    }
    input_file.close();
    return true;
} // manca da fare funzione doSimulation che  printa le uscite per ogni colpo di clock

bool Circuit :: buildGraph(){
    bool module_flag=false;
    string word,line;
    int i=0;
    if (_my_file.is_open()){
        while (getWord(word)) {
            if (word=="module") {//controlla se la prima parola è module;
                getWord(word); // nome circuito --
                getWord(word); // {
                if (word=="{") {
                    while (getWord(word)) {//se hai trovato la {, leggi le parole finchè non trovi } o finisce il file
                        //leggi linea e assegna ingressi/uscite tramite ricerca nel dizionario
                        if (word=="}") break;
                        i=0;
                        do{
                            if (word==_dictionary[i]) break;
                            i++;
                        }while (i<3);
                        //confronta la parola trovata con il dizionario : clk, input, output
                        if (i == 3) {//se i=3, sei uscito dal ciclo senza trovare una di quelle parole: devi dare errore
                            cout<< "errore negli input/output del circuito";// trovata una parola che non è input output o clock
                            return false;
                        } else doOp(i);// passa indirizzo del vettore che matcha con la parola trovata e fa operazioni : se clock è sequenziale, se inp aggiungi elemento in vett input, idem con out
                    }//sei uscito dal ciclo perché è finito il file o hai trovato }
                    if (word != "}") {
                        cout << "errore formattazione file : expected '}' ";
                        return false;    //sei uscito dal ciclo senza trovare }: arrivato a end file senza }
                    }
                }else{
                    cout<<"errore: expected { missing";
                    return false;
                }
                getWord(word);//appena uscito dal ciclo, dopo aver trovato } deve esserci ';'
                if (word != ";") {
                    cout << "error : expected ';' after }";
                    //return false;
                }
                //da aggiungiwew: funzione sarà bool e va avanti solo se è buona, agli errori fare return 1
                module_flag= true;
            }else if (!module_flag){
                cout<<"errore: "<<word<<"prima parola deve essere 'module'";
                return false;
            }
            //finito confronto di module, ora trova assign o ff o end module o instance :
            //ho già una parola, la confronto con assign, ff, endmodule, istance
            if (module_flag){
                getWord(word);
                i=3;
                do{
                    if (word.compare(_dictionary[i])==0) break;
                    if (i==6) //se è ff deve controllare solo i primi due caratteri
                        if (strncmp (word.c_str(),_dictionary[i].c_str(),2) == 0) doOp(i); //trovato ff: strncmp compare i primi due caratteri
                    i++;
                }while (i<7);
                if (i == 7){ cout << "errore: non ci sono";
                }else {
                    doOp(i); // ho trovato una parola valida, ora fai le operazioni di : input, output, ff, assign
                }
            }
        }
        return true;
    }else{
        cout<<"Error: file not found";
        return false;
    }

}


bool Circuit :: assign(Component *head){
    char *pch;
    char buffer[200];
    string line;
    int i=0,address;
    Component* cpPtr;
    cpPtr= nullptr;
    bool Aflag= false;
    queue<string> output_queue;
    stack<string> operator_stack;
    stack<Component*> address_stack;
    getline(_my_file,line);
    strcpy(buffer,line.c_str());
    pch = strtok(buffer, " ");
    while(pch != nullptr) {
        //shunting-yard
        if (pch=="(") {
            operator_stack.push(pch);
            break;
        }
        if (pch==")"){
            while(operator_stack.top()!="("){
                output_queue.push(operator_stack.top());//estrai l'ultimo elemento dello stack e mettilo in output
                operator_stack.pop();
            }
            if (operator_stack.empty()){
                cout<<"errore: mismatching '(' in assign";
                return false;
            }
            operator_stack.pop();//elimina '('
            break;
        }
        i=0;
        while (i<_input_vector.size()){
            if (pch==_input_vector[i].name){ //se è un ingresso,
                output_queue.push(pch);
                break;
            }
            i++;
        }
        i=0;
        while(i<dict_lenght){
            if (pch==_gate[i]) {
                while ((!operator_stack.empty() /*||*/ /*operator_stack.top().c_str() == "not"*/) && (operator_stack.top().c_str() != "(")) {
                    output_queue.push(operator_stack.top());//estrai l'ultimo elemento dello stack e mettilo in output
                    operator_stack.pop();
                }
                operator_stack.push(pch);
                break;
            }
            i++;
        }

        pch = strtok(nullptr, " ");
    }
    while (!operator_stack.empty()){
        output_queue.push(operator_stack.top());//estrai l'ultimo elemento dello stack e mettilo in output
        operator_stack.pop();
    }
    //a questo punto ho output queue in ordine: costruisci albero
    //creo stack: metto component, quando trovo un operatore faccio pop degli ultimi due
    while(!output_queue.empty()){
        if(output_queue.size()==1){
             tree(checkOperator(output_queue.front()), address_stack);
         }
        if (checkOperator(output_queue.front())>=0){  //trovato un operatore in _gate vector (checkoperator da -1 se non trova gate, indirizzo nel vettore se lo trova
            tree(checkOperator(output_queue.front()), address_stack);//costruito alberp, attenzione a non perdere le teste:
            if (output_queue.size()==1){// se è l'ultimo elemento, mantieni la testa del grafo
                head=address_stack.top();
            }
            output_queue.pop();
        }
        address = checkInput(output_queue.front());
        if (address>=0){
            cpPtr=_input_vector[address].data;
            address_stack.push(cpPtr);//puntatore a elemento di input vector
            output_queue.pop();
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
bool Circuit :: doOp(int& i){//{"0clk","1input","2output","3assign","4instance","5endmodule", "6ffx", "7and","8or", "9xor","10not","11nand","12nor","13xnor"};
    string word;
    int c=0;
    bool flag= false;
    switch (i){

        case 0: _sequenziale=true;
            break;
        case 1: getWord(word);
            if (word==":"){
                makeVectors(i);
            }
            break;//input
        case 2: getWord(word);
            if (word==":"){
                makeVectors(i);
            }
            break;//output
        case 3: getWord(word);
            //leggi elemento di output vector, controlla se c'è
            c=0;
            do{
                if (word.compare(_output_vector[c].name.c_str())==0) {
                    flag = true;
                    break;
                }
                c++;
            }while(c<_output_vector.size());
            if (!flag) {//uscito dal ciclo senza trovare output definito
                cout << "errore: output '" << word << "' non definito";
                return false;
            }
            //RICOMINCIARE DA QUI: CHECK DELL'ELEMENTO NEL VETTORE USCITE, DOPODICHè IMPLEMENTAZIONE SHUNTING-YARD
            getWord(word);//leggi '='
            if (!(word=="=")){
                cout<<"errore: inserire '=' dopo "<<_output_vector[c].name;
                return false;
            }
            assign(_output_vector[c].data);
            //assign()
            break; //assigncase 4: break; //istance
        case 5:_sequenziale=true;
            break;//endmodule
        case 6:_sequenziale=true;
            break;//ff
        default: break;
    }

}


bool myispunct(char ch) { return std::ispunct(ch) && ch != '_'; }
bool Circuit :: getWord(string& word) { //estrae una parola e rende tutti i caratteri minuscoli
    word.clear();
    char ch;
    while (_my_file.get(ch) && isspace(ch)); //scorre il file finché elimina gli spazi
    if (isalpha(ch)) ch = tolower(ch);
    if (_my_file) word += ch;
    if (!myispunct(ch)) {
        while (_my_file.get(ch)) {
            if (isalpha(ch)) ch = tolower(ch);
            // for ( ; _my_file.get(ch); word += ch)
            if (isspace(ch) || myispunct(ch)) { // or myispunct
                if (ispunct(ch)) _my_file.putback(ch);
                break;
            }
            word += ch;
        }
    }
    return word.size() !=0;
}

void Circuit :: makeVectors(int& i){
    char *pch;
    char buffer[200];
    string line;
    int j=0;
    getline(_my_file,line);
    strcpy(buffer,line.c_str());
    pch = strtok(buffer, ", ");
    while(pch != nullptr){
        if(i==1) {
            j = _input_vector.size();
            _input_vector.push_back( { pch, new ConstantComponent } );
        }else{
            j= _output_vector.size();
            _output_vector.push_back( { pch, new ConstantComponent } );
        }
        pch = strtok(nullptr, ",");
    }
}

void Circuit :: setFileName(){
    string nomefile;
    cout<<"Insert file's name to open: ";
    cin>>nomefile;
    _file_name=nomefile;
}

void Circuit :: openFile()  {
    _my_file.open(_file_name.c_str(), ios:: in);
    if (!_my_file.is_open()) cout<<"unable to open file";
}

void Circuit :: closeFile() {
    _my_file.close();
}

int Circuit :: checkOperator(string& operatore){
    // if
    for (int i=0;i<dict_lenght;i++){
        if (_gate[i]==operatore) {
            return i;
        }
    }
    return -1;
}

int Circuit :: checkInput(string &word){
    for (int i=0; i<dict_lenght; i++){
        if (_input_vector[i].name==word){
            return i;
        }
    }
    return -1;
}


void Circuit :: tree(int address, stack<Component*> stack) { //and","or", "xor","nand","nor","xnor"};
    Component* temp= nullptr;
    Not *pNot = new Not;
    And *pAnd = new And;
    Or *pOr = new Or ;
    Xor *pXor = new Xor;
    Nand *pNand = new Nand;
    Nor *pNor = new Nor;
    Xnor *pXnor = new Xnor;
    switch (address) {
        case 0:
            temp=stack.top();
            pNot->setInputs(*temp);
            stack.pop();
            stack.push(pNot);
            break;
        case 1:
            temp=stack.top();
            stack.pop();
            pAnd->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pAnd);
            break;
        case 2:
            temp=stack.top();
            stack.pop();
            pOr->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pOr);
            break;
        case 3:
            temp=stack.top();
            stack.pop();
            pXor->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pXor);
            break;
        case 4:
            
            temp=stack.top();
            stack.pop();
            pNand->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pNand);
            break;
        case 5:
            
            temp=stack.top();
            stack.pop();
            pNor->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pNor);
            break;
        case 6:
            
            temp=stack.top();
            stack.pop();
            pXnor->setInputs(*stack.top(), *temp);
            stack.pop();
            stack.push(pXnor);
            break;
        default:break;
    }
}
that's the file to be read:

Module circuit
{
input : x ,y
output : z
};

assign z = x and y
endmodule
main.cpp:
1
2
3
4
5
6
#include "Circuit.h"
#include "Component.h"
int main() {
    Circuit circuito;
    return 0;
}
Last edited on
maybe with all of the code you can help me, maybe there are less errors.
Circuit :: tree is full of memory leaks. All those objects made with new, and then lost. This is bad.
Yeah the code it's not finished, but my will was to delete them after
How about just create the one that you need?
Maybe I'm missing something, but why does Component have a pointer to a Component?

Why does Add also have a pointer to a Component when it is already a Component?

Your Circuit class needs to be simplified. I suggest more functions to split some of those "big" monsters into something more manageable.


Edit:
Yeah the code it's not finished, but my will was to delete them after

The longer you wait the larger the probability that you never accomplish the task.
Last edited on
I would re-do main and slowly exercise the code.
make one object in main, and see if you can run a few methods on that without failures. Find problems and fix them. Use the compiler warnings, about 3/4 of them as listed above are 'real' problems and generally most coders fix all warnings to be sure they don't have bugs, even when 'fixing' them is just a cast or the like, it makes you double check the issue.

slowly rebuild main until it fails. Then stop and find and fix what you just did that caused a problem.
Last edited on
How about just create the one that you need?

I could put them in switch case, but I obtain other problems: cross initialitation I think.

but why does Component have a pointer to a Component?

I need to build a binary tree and make BFS then.
The target is to build a simulator than simulate circuits, can use other circuits defined in past to build composed circuits, find longest path and shortest path.
If you have some ideas about how to do that, please help me cause again, I'm very disperated..
I need to do this in 3/4 days or I can't get graduated. Help me.

I would re-do main and slowly exercise the code.

I will re-start from there
Pages: 12