错误:
Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.
这似乎是本论坛的常见错误;但是,我无法找到其中混有汇编代码的代码。基本上,我的程序是将十进制转换为二进制(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;
}
汇编代码:
.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
最佳答案
我没有汇编程序来编译您的代码,但是您在这一行将 32 位值写入 char[]
:
mov [eax],ebx ;Copy the 0's or 1's into the array location
因此,最后一次写入会将内存位置
arr[SIZE-1]
更新为 arr[SIZE+2]
。关于c++ - x86 Intel Assembly 和 C++ - 阵列周围堆栈损坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33790106/