int a=11;
int b=22;
int c=33;
int d=44;
アセンブリを見ると変数はスタックの以下の位置に保存されている。
順番に配置されるとは限らないことが分かる。
a : [r7, #20]
b : [r7, #16]
c : [r7, #12]
d : [r7, #4]
movs r3, #11
str r3, [r7, #20]
movs r3, #22
str r3, [r7, #16]
movs r3, #33
str r3, [r7, #12]
movs r3, #44
str r3, [r7, #4]
以下のようにしてポインタを変数dに合わせ、2を足す(4byte×2)と変数cの中身を表示できる
[r7, #4]
から[r7, #12]
へ合わせる為に2を足す
int *p=&d;
p = p + 2;
printf("%d",*p);
testuser@CasaOS:~/test$ gcc test.c
testuser@CasaOS:~/test$ ./a.out
33testuser@CasaOS:~/test$
ソース全体
アセンブリを出力する命令
gcc -O0 -S test.c -o test.s
test.c
#include<stdio.h>
int main(){
int a=11;
int b=22;
int c=33;
int d=44;
int *p=&d;
p = p + 2;
printf("%d",*p);
return 0;
}
test.s
.arch armv7-a
.fpu vfpv3-d16
.eabi_attribute 28, 1
.eabi_attribute 20, 1
.eabi_attribute 21, 1
.eabi_attribute 23, 3
.eabi_attribute 24, 1
.eabi_attribute 25, 1
.eabi_attribute 26, 2
.eabi_attribute 30, 6
.eabi_attribute 34, 1
.eabi_attribute 18, 4
.file "test.c"
.text
.section .rodata
.align 2
.LC0:
.ascii "%d\000"
.text
.align 1
.global main
.syntax unified
.thumb
.thumb_func
.type main, %function
main:
@ args = 0, pretend = 0, frame = 24
@ frame_needed = 1, uses_anonymous_args = 0
push {r7, lr}
sub sp, sp, #24
add r7, sp, #0
movs r3, #11
str r3, [r7, #20]
movs r3, #22
str r3, [r7, #16]
movs r3, #33
str r3, [r7, #12]
movs r3, #44
str r3, [r7, #4]
adds r3, r7, #4
str r3, [r7, #8]
ldr r3, [r7, #8]
adds r3, r3, #4
str r3, [r7, #8]
ldr r3, [r7, #8]
ldr r3, [r3]
mov r1, r3
ldr r3, .L3
.LPIC0:
add r3, pc
mov r0, r3
bl printf(PLT)
movs r3, #0
mov r0, r3
adds r7, r7, #24
mov sp, r7
@ sp needed
pop {r7, pc}
.L4:
.align 2
.L3:
.word .LC0-(.LPIC0+4)
.size main, .-main
.ident "GCC: (Debian 12.2.0-14+deb12u1) 12.2.0"
.section .note.GNU-stack,"",%progbits