为什么我在程序集中的嵌套 for 循环会导致无限循环
Why do my nested for loops in assembly result in an infinite loop
我的程序是用C++编写的,其中嵌入了一些x86汇编语言。我有 2 个嵌套的汇编语言 for 循环,我必须通过。但是,当我编译程序时,我得到了一个无限循环。C++中的等效程序如下所示:
#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;
}
为什么这会导致无限循环?
您至少需要解决两件事:
-
调用
output()
时,只能保证以下寄存器不会被丢弃:-
edi
、esi
、ebx
和ebp
特别是,您正在使用
ecx
,允许该函数将其丢弃。 -
-
永远不会将
counter2
重置为 0,因此内部循环不等同于 C 代码。
我相信
这里的答案是,在调用函数Output
和MakeSpace
之前,您永远不会保留寄存器。 标准函数标头不保证有关asm
代码中使用的ecx
或ebx
寄存器的任何信息。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- C++ Python 循环"for i, num in enumerate(list):"版本
- C 多循环 for () 基础知识
- 没有条件值的 FOR 循环"for (int i = 1; ; i++)"无法正常工作
- 为用户提供循环for循环的选项
- 打破循环for循环