【发布时间】:2025-11-27 16:30:01
【问题描述】:
这是 c++ 文件:
#include <iostream>
using namespace std;
//This is the C prototype of the assembly function, it requires extern"C" to
//show the name is going to be decorated as _test and not the C++ way of
//doing things
extern"C"
{
//char arrayReverse(char*, int);
int numChars(char *, int);
char swapChars(char *, int);
}
int main()
{
const int SIZE = 7;
char arr[SIZE] = { 'h', 'e', 'l', 'l', 'o', '1', '2' };
int val1 = numChars(arr, SIZE);
cout << "The number of elements is: " << val1 << endl;
char val2 = swapChars(arr, SIZE);
cout << "Swapped! " << endl;
return 0;
}
还有我的 swapChars() 文件:
.686
.model flat
.code
_swapChars PROC ; named _test because C automatically prepends an underscode, it is needed to interoperate
push ebp
mov ebp,esp ; stack pointer to ebp
mov ebx,[ebp+8] ; address of first array element
mov ecx,[ebp+12] ; number of elements in array
mov ebp,0
mov eax,0
mov edx,ebx ;move first to edx
add edx, 7 ;last element in the array
loopMe:
cmp ebp, ecx ;comparing iterator to total elements
jge nextLoopMe
mov eax, [ebx] ;move 1st element into tmp eax
mov ebx, [edx] ;move last element into first
mov edx, eax ;move tmp into last
push ebx ;push first element onto stack
add ebx, 1 ;first + 1
sub edx, 1 ;last - 1
add ebp, 1 ;increment
jmp loopMe
nextLoopMe:
mov ebx,[ebp+8] ;find first element again USING AS FFRAME POINTER AGAIN
cmp ebx, ecx ;comparing first element to number of elements
je allDone
pop ebx
add ebx, 1
jmp nextLoopMe
allDone:
pop ebp
ret
_swapChars ENDP
END
这应该取 arr[0] 中的值并将其与 arr[6]、arr[1] 与 arr[5] 等交换,直到整个数组被交换然后显示它。我不知道我写的任何代码是否能做任何我想做的事情,但我正在寻找一种方法来看看发生了什么。
有没有一种方法可以让 asm 代码在遍历循环时将内容打印到控制台?
寄存器 ( [ebx] ) 周围的括号是否表示寄存器的值?
在loopMe:中时,第三行
mov eax, [ebx]
我得到一个异常“在 assignment4.exe 中的 0x012125FC 抛出异常:0xC0000005:访问冲突读取位置 0xCCCCCCCD。”
我是否正确处理掉期?
感谢您的宝贵时间。
【问题讨论】:
-
使用调试器单步调试代码。
[ebx]是地址ebx的内存访问 - 如果您遇到异常,则意味着ebx不指向有效内存。您还应该阅读有关调用约定的信息,必须保留一些寄存器(包括ebx)。将ebp归零似乎也不是一个好主意,尤其是当您以后想将其用作指针时。 -
你到底为什么要在汇编程序中实现这些功能??
-
肯定是学校作业什么的。其实这些都是很好的学习经验,恕我直言。
-
所以,现在我无法将寄存器的值显示到控制台。我能做什么?
标签: c++ arrays assembly swap masm