Reputation: 1201
I want to know how to find the value of the constant M
from the following c and corresponding assembler code. Is there any method to determine M
just by analysing the code?
#include<stdio.h>
int main(){
int i=7;
int a[14];
a[i] = 99;
int b[M];
b[i] = 88;
}
Assembly code given
main :
endr64
pushq %rbp
movq %rsp, %rbp
subq $80, %rsp
movl $7, -80(%rbp)
movl -80(%rbp), %eax
cltq
movl $99, -64(%rbp,%rax,4)
movl -80(%rbp),%eax
cltq
movl $88, -76(%rbp,%rax,4)
movl $0,%eax
leave
ret
Upvotes: 0
Views: 207
Reputation: 5557
Think what is the format of the stack due to the allocation for the variables.
You can see that i
is located on -80 from the stack pointer rbp
. Also you can see that the a[0]
is located at -64 (see movl $99, -64(%rbp,%rax,4)
), and b[0]
is located on -76 (see movl $99, -76(%rbp,%rax,4)
). So, the start of b is located -12 bytes from the start of a, meaning, the length of b is 12 bytes.
Next you need to know is that the size of int
is 4, so 12/4 = 3, therefore M
was 3.
Use gcc -S
on the following code and you can verify.
#include<stdio.h>
#define M 3
int main(){
int i=7;
int a[14];
a[i] = 99;
int b[M];
b[i] = 88;
}
Upvotes: 3
Reputation: 5795
Perhaps this picture of stack layout might help:
--------------------
| return from main |
--------------------
| pushed RBP |
--------------------
RBP-08|RBP-04 | | |
--------------------
RBP-16|RBP-12 | a[12] | a[13] |
--------------------
RBP-24|RBP-20 | a[10] | a[11] |
--------------------
RBP-32|RBP-28 | a[8] | a[9] |
--------------------
RBP-40|RBP-36 | a[6] | a[7] |
--------------------
RBP-48|RBP-44 | a[4] | a[5] |
--------------------
RBP-56|RBP-52 | a[2] | a[3] |
--------------------
RBP-64|RBP-60 | a[0] | a[1] |
--------------------
RBP-72|RBP-68 | b[1] | b[2] |
--------------------
RBP-80|RBP-76 | i=7 | b[0] |
--------------------
a[7] is addressed as RBP-36 and b[7] would be addressed as RBP-48 (if only array b[] would have been allocated this big).
Upvotes: 3