I’m writing a code for a MIPS pipeline simulator in C++. One of my functions is fetch. After some debugging, I narrowed down to my fetch function, where the segmentation fault occurs. Can someone help me figure out why it happens? The code is here below:
void Simulator::fetch(){
int flag =0;
string buf, rd;
int i;
for(i = 0;i<4;i++){
if(pre_issue_buffer[i]==";"){
flag = 1;
break;
}
}
if(flag ==1){
if(i<3){
string instr = memory.read_memory(PC);
stringstream ss(instr);
vector<string> tokens;
while (ss >> buf)
tokens.push_back(buf);
string instruction = tokens.at(0);
if(instruction == "BREAK"){
brk =1;
instr_string=instruction;
}
else if(instruction=="NOP"){
instr_string=instruction;
}
else if(instruction=="J"){
int address=toInt(tokens.at(1));
if(address>this->break_addr){
cerr<<"Invalid Jump Address at: "<<PC<<endl;
}
PC = address;
exec_instr=instruction+"\t#"+tokens.at(1);
}
else if(instruction=="JR"){
rd = tokens.at(1);
if(regInUse[rd]==0){
p=regFile.find(tokens.at(1));
PC = p->second;
exec_instr=instruction+"\t"+tokens.at(1);
}
else
waiting_instr= instruction+"\t"+tokens.at(1);
}
else if(instruction=="BEQ"){
int rs,rt;
rd = tokens.at(1);
if(regInUse[rd]==0){
p=regFile.find(tokens.at(1));
rs = p->second;
p=regFile.find(tokens.at(2));
rt = p->second;
if(rs==rt){
int offset=toInt(tokens.at(3));
PC = PC+offset+4;
}
else
PC=PC+4;
exec_instr=instruction+"\t"+tokens.at(1)+", "+tokens.at(2)+", #"+tokens.at(3);
}
else
waiting_instr=instruction+"\t"+tokens.at(1)+", "+tokens.at(2)+", #"+tokens.at(3);
}
else if(instruction=="BLTZ"){
rd = tokens.at(1);
if(regInUse[rd]==0){
p = regFile.find(tokens.at(1));
int rs = p->second;
if(rs<0){
int offset=toInt(tokens.at(2));
PC = PC + offset+4;
}
else
PC=PC+4;
exec_instr=instruction+"\t"+tokens.at(1)+", #"+tokens.at(2);
}
else
waiting_instr=instruction+"\t"+tokens.at(1)+", #"+tokens.at(2);
}
else if(instruction=="BGTZ"){
rd = tokens.at(1);
if(regInUse[rd]==0){
p = regFile.find(tokens.at(1));
int rs = p->second;
if(rs>0){
int offset=toInt(tokens.at(2));
PC = PC + offset+4;
}
else
PC=PC+4;
exec_instr=instruction+"\t"+tokens.at(1)+", #"+tokens.at(2);
}
else
waiting_instr=instruction+"\t"+tokens.at(1)+", #"+tokens.at(2);
}
else{
rd = tokens.at(1);
pre_issue_buffer[i]=instr;
cout<<i<<endl;
PC=PC+4;
}
}
Check, for every array, the position you are trying to access and verify it’s inside the array bounds.
We don’t have enough informations to answer. For what I can tell it may be at the beginning as well as at the end of your function.