简体   繁体   中英

How to find array size by analysing assembler and C code

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

在此处输入图像描述

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;
 }

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM