x86英特尔汇编和C++ - 堆栈数据损坏

And*_*yen 3 c c++ assembly

错误:

Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.
Run Code Online (Sandbox Code Playgroud)

这似乎是这个论坛上的一个常见错误; 但是,我无法找到一个混合了汇编代码的程序.基本上,我的程序是将十进制转换为二进制(16位表示).完成编码后,一切似乎都正确计算并将十进制转换为二进制而没有问题; 然而,在"按任意键继续......"之后.,弹出上面的错误.

我不相信C++代码导致问题,因为它是非常基本的,并且仅用于调用汇编函数.

再次,计算是正确的,因为程序将产生正确的转换(即:十进制= 10,二进制转换:0000000000001010),但只是在程序结束时给我错误.

C++代码:

#include <iostream>

using namespace std;

extern"C" void decToBin(char[], int, int);

int main()
{
//Initialize array and variables
const int SIZE = 16;
char arr[SIZE] = { NULL };
int dec = 0;

//Ask user for integer that they want to convert
cout << "Please enter integer you want to convert to binary: ";
cin >> dec;

//Assembly function to convert integer
decToBin(arr, dec, SIZE);

cout << "The 16-bit binary representation of " << dec << " is: ";

//Display the 16-bit binary conversion
for (int i = 0; i < SIZE; i++)
    cout << arr[i];

cout << endl;

system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)

汇编代码:

.686
.model flat

.code

_decToBin PROC              ;Start of project

start:
push ebp
mov ebp,esp             ;Stack pointer to ebp

mov eax,[ebp+8]         ;Address of first array element
mov cx,[ebp+12]         ;Integer number being passed - Copying onto 16 bit register
mov edx,[ebp+16]        ;Size of array

loopme:                     ;Loop to fill in array
mov ebx,0               ;Initializes ebx to store carry flag after shift
cmp edx,0               ;Compare edx with 0 to see if we should continue
je alldone              

shl cx,1                ;Shift the value to the left
adc ebx,0               ;Check carry flag and add 1 if CF(CY) is set to 1 and stay at 0 if CF(CY) is 0
add ebx,48              ;Since array is CHAR, adding 48 will give correct 0 or 1 instead of null

mov [eax],ebx           ;Copy the 0's or 1's into the array location

dec edx                 ;Decrement the counter
inc eax                 ;Move the array up an index

jmp loopme

alldone:    
pop ebp
ret

_decToBin ENDP

END
Run Code Online (Sandbox Code Playgroud)

Mar*_*bel 6

我没有汇编程序来编译你的代码,但你char[]在这一行写了32位值:

mov [eax],ebx           ;Copy the 0's or 1's into the array location
Run Code Online (Sandbox Code Playgroud)

所以,最后写入将更新的存储位置arr[SIZE-1]arr[SIZE+2].