2012-09-21 123 views
-1

我的程序是用C++編寫的,其中嵌入了一些x86彙編語言。我有兩個嵌套的彙編語言循環,我必須經過。然而,當我編譯我的程序時,我會遇到一個無限循環。在C++中的等效方案將是這個樣子:爲什麼我的彙編嵌套for循環導致無限循環

#include<iostream> 
using namespace std; 
int main() 
{ 
    int a[4] = {3,6,4,7}; 

    for(int k = 0 ; k < 4;k++) 
    { 
     for(int l = 0 ; l < a[k];l++) 
     { 
      cout<<'*'; 
     } 
     cout<<endl; 
    } 

    system("pause"); 
    return 0; 
} 

/* 

    *** 
    ****** 
    **** 
    ******* 
    Press any key to continue . . . 
    */ 

這是同樣的事情,但裝配完成混合

#include<iostream> 
using namespace std; 
void output(); //function for making an '*' 
void makeSpace(); //function for making a space 

int main() 
{ 
    int a[4]={3,6,4,7}; 

    int counter = 0; //counter that will be used for first forloop 
    int counter2 = 0; // counter to be used for second forloop 

_asm{ 

    mov ebx,0 // this is to move from element 0,1,2,3,4, through the array 
    mov ecx,0 // ecx will get the data from the array, only to be used as a 
       // counter in forloop2 though. 

    for1: 

    cmp counter,4 //begins for firloop 

    je starts 
    mov ecx,[a+ebx] // move the 0th element from array to ecx 
    add ebx,4// ebx = ebx+4, I'm doing this to advance the array position (int) 
    inc counter// increment counter by one 

     for2: 
    cmp counter2,ecx //begin forloop2, 
    je starts2 
    call output 
    inc counter2 //increment counter2 by one 

    jmp for2 
     starts2: 

    call makeSpace 
    jmp for1 
     starts: 
} 

    return 0; 
} 

void output() 
{ 
    cout<<'*'; 
    } 

void makeSpace() 
{ 
    cout<<endl; 
} 

爲什麼這會導致一個無限循環?

+0

兩件事情(1)這不是論壇,不需要介紹自己或向我們問好; (2)你的問題到底是什麼? – user7116

+3

請添加一個實際的信息標題關於你要問什麼。你目前擁有的不是一個標題。請妥善格式化並縮進您的代碼。 – Bart

+0

您是否嘗試構建C++版本並檢查編譯器生成的程序集? – mah

回答

2

至少有兩件事情你需要修復:

  • 當你調用output()只有以下寄存器保證無法刪除:

    • ediesiebxebp

    尤其是,您使用的是ecx,該功能被允許垃圾。

  • 您永遠不會將counter2重設爲0,因此內循環不等同於您的C代碼。

+0

謝謝,你解決了這個問題。 – chucknorris

0

我相信這裏的答案是,你永遠不會調用函數OutputMakeSpace之前保存您的寄存器。標準函數頭文件不保證asm代碼中使用的ecxebx寄存器的任何內容。