Let's imagine I define a local array of int
s with a default value of 0 in my function:
void test() {
int array[256] = {0};
}
My understanding of this is that:
the array will be stored in the stack, by pushing 256 zeroes to the stack and consequently increasing the stack pointer. If there was no default value for the array, increasing the stack pointer would have been enough.
Now this is the assembly code produced by the previous snippet:
test:
.LFB2:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
pushl %edi
pushl %ebx
subl $1024, %esp
.cfi_offset 7, -12
.cfi_offset 3, -16
leal -1032(%ebp), %ebx
movl $0, %eax
movl $256, %edx
movl %ebx, %edi
movl %edx, %ecx
rep stosl
addl $1024, %esp
popl %ebx
.cfi_restore 3
popl %edi
.cfi_restore 7
popl %ebp
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE2:
.size test, .-test
I realize this may be a silly question and I am aware that each compiler may act differently, but I'm wondering where the allocation of the array with 256 zeros is happening. Were my assumptions correct or this is happening differently?
(I've not been writing assembly for quite a long time and I'm having some difficulties understanding what's going on)
The allocation is happening here:
subl $1024, %esp
It is a sub
on the stack pointer esp
, because a stack grows down.
The array is cleared here:
movl $0, %eax
movl $256, %edx
movl %ebx, %edi
movl %edx, %ecx
rep stosl
What this does is:
rep
: repeat the string operation ecx
timesstosl
: store eax
in the memory pointed to by edi
and add 4 to edi, or subtract 4, depending on the direction flag. If it's clear (cld
), edi
gets incremented, and decremented otherwise. Note that ebx
is set to point to the start of the array a bit earlier in the code.And finally, here the array is released:
addl $1024, %esp
pushl %ebp # preserve caller's ebp (decrements esp by 4)
movl %esp, %ebp # copy stack pointer to ebp
pushl %edi # preserve for caller
pushl %ebx # preserve for caller
subl $1024, %esp # allocate 1kb on the stack
leal -1032(%ebp), %ebx # esp + 1024 + 4 + 4 = ebp; equivalent to mov %esp, %ebx
movl $0, %eax # the {0}
movl $256, %edx # the repeat count - could have been stored in ecx directly
movl %ebx, %edi # init edi to the start of the array
movl %edx, %ecx # put 256 in ecx
rep stosl # repeat 'mov %eax, %(edi); add $4, %edi' ecx times
addl $1024, %esp # release the array
popl %ebx # and the preserved registers
popl %edi
popl %ebp
ret
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments