1.20. ARRAYS
la $s3, $LC0 # "a[%d]=%d\n"
; "i" variable will reside in $s0:
move $s0, $zero
li $s2, 0x14
loc_54: # CODE XREF: main+70
; call printf():
lw $t9, (printf & 0xFFFF)($gp)
lw $a2, 0($s1)
move $a1, $s0
move $a0, $s3
jalr $t9
; increment "i":
addiu $s0, 1
lw $gp, 0x80+var_70($sp)
; jump to loop body if end is not reached:
bne $s0, $s2, loc_54
; move memory pointer to the next 32-bit word:
addiu $s1, 4
; function epilogue
lw $ra, 0x80+var_4($sp)
move $v0, $zero
lw $s3, 0x80+var_8($sp)
lw $s2, 0x80+var_C($sp)
lw $s1, 0x80+var_10($sp)
lw $s0, 0x80+var_14($sp)
jr $ra
addiu $sp, 0x80
$LC0: .ascii "a[%d]=%d\n"<0> # DATA XREF: main+44
Something interesting: there are two loops and the first one doesn’t needi, it needs onlyi∗ 2 (increased
by 2 at each iteration) and also the address in memory (increased by 4 at each iteration).
So here we see two variables, one (in $V0) increasing by 2 each time, and another (in $V1) — by 4.
The second loop is whereprintf()is called and it reports the value ofito the user, so there is a variable
which is increased by 1 each time (in $S0) and also a memory address (in $S1) increased by 4 each time.
That reminds us of loop optimizations we considered earlier:3.7 on page 490.
Their goal is to get rid of multiplications.
1.20.2 Buffer overflow.
Reading outside array bounds
So, array indexing is justarray[index]. If you study the generated code closely, you’ll probably note the
missing index bounds checking, which could checkif it is less than 20. What if the index is 20 or greater?
That’s the one C/C++ feature it is often blamed for.
Here is a code that successfully compiles and works:
#include <stdio.h>
int main()
{
int a[20];
int i;
for (i=0; i<20; i++)
a[i]=i*2;
printf ("a[20]=%d\n", a[20]);
return 0;
};
Compilation results (MSVC 2008):