2012-09-21 56 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寄存器的任何内容。