我有以下返回9的C代码:
#include <stdio.h>
int main()
{
int array[4]={0};
array[2]=9;
return array[2];
}
为实现相同的汇编语言,我尝试过:
.section .data
array: .zero 4
.section .text
.globl _start
_start:
mov $2,%esi
mov array(,%esi,4),%ecx # copy address of array[2] to %ecx
mov $9,%ecx
mov $1,%eax
mov array(,%esi,4),%ebx # return the value of array[2]
int $0x80
组装并链接到:
gcc -g -c array.s && ld array.o && ./a.out
但是此程序返回0
而不是9
:
>./a.out
>echo $?
0
我怀疑问题出在注释中。在尝试了各种失败的尝试之后,我决定问一个问题:如何在汇编中更改数组元素(在这种情况下为array[2]
)的值?
答案 0 :(得分:0)
.section .data
array: .zero 16 # allocate 16 bytes instead of 4
.section .text
.globl _start
_start:
mov $2,%esi
lea array(,%esi,4),%ecx # copy address of array[2] to %ecx, not the value
mov $9, %ebx
mov %ebx,(%ecx) # assign value into the memory pointed by %ecx
mov $1,%eax
mov array(,%esi,4),%ebx
int $0x80