我无法弄清楚如何打印数组,反过来,我无法弄清楚如何交换数组中的元素

时间:2015-11-06 17:11:30

标签: c++ arrays assembly swap masm

这是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]

我得到一个异常&#34;在assignment4.exe中0x012125FC处抛出异常:0xC0000005:访问冲突读取位置0xCCCCCCCD。&#34;

我是否正确处理掉期?

感谢您的时间。

2 个答案:

答案 0 :(得分:3)

您确实需要学习使用调试器来逐步完成此操作。也就是说,这是我看到的一些问题。

add edx,7

将指向edx超过数组的末尾。就像C代码中的arr[7]一样。应该add edx,6将edx指向最后一个字符。

在你的触发过程中,它很容易发生变化ebp,我认为你有错误。您更改了它的值,但随后希望[ebp+8]稍后引用相同的数据。

您也没有正确修改列表。要将char从一个元素移动到另一个元素,您可以执行以下操作:

mov al, [ebx]     ; copy byte from address ebx to register al
mov [edx], al     ; copy byte in register al into address edx

eax寄存器为32位,一次复制4个字节,而不是1个。

答案 1 :(得分:-2)

首先,您的代码不安全,因为您忘记在char数组的末尾添加\ 0。当您使用函数来处理您的char或char字符串时,它将启动内存泄漏。大小应为8,数组中的最后一个应为\ 0。