2012-04-11 43 views
0

我正在寫一個MIPS管道模擬器在C++中的代碼。我的一個功能是抓取。經過一些調試後,我縮小了我的抓取功能,發生分段錯誤。有人能幫我弄清楚爲什麼會發生?該代碼是在這裏如下:需要幫助找出爲什麼我得到這個分段錯誤

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; 
} 

}

+0

你編譯調試?你有核心轉儲嗎?你可能會嘗試使用調試器(例如gdb),讓機器人更接近錯誤。 – gbulmer 2012-04-11 18:37:52

+0

我如何使用gdb來接近錯誤,我沒有使用gdb太多,我用backtrace來發現錯誤在這個函數中,但我該怎麼做呢? – Chaos 2012-04-11 18:39:03

回答

1

檢查,對於每一個陣列,您試圖訪問和驗證它的數組邊界內的位置。

我們沒有足夠的信息來回答。對於我可以告訴它可能是在你的函數的開始和結束。

+0

沒關係,我在這裏使用的唯一數組是pre_issue_buffer,它可以包含最多4個元素。 regInUse和Memory是地圖對象,我之前測試過它們,所以我不認爲它們應該創建錯誤 – Chaos 2012-04-11 18:41:32