为什么编译器会保留少量堆栈空间,而不保留整个数组大小? [英] Why does the compiler reserve a little stack space but not the whole array size?

查看:122
本文介绍了为什么编译器会保留少量堆栈空间,而不保留整个数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

int main() {
  int arr[120];
  return arr[0];
}

编译为:

  sub     rsp, 360
  mov     eax, DWORD PTR [rsp-480]
  add     rsp, 360
  ret

知道int是4个字节,数组的大小为120,数组应该占用480个字节,但是从ESP中仅减去360个字节...为什么?

Knowing the ints are 4 bytes and the array is size 120, the array should take 480 bytes, but only 360 bytes are subtracted from ESP... Why is this?

推荐答案

在函数使用的堆栈区域下面,有一个

Below the stack area used by a function, there is a 128-byte red zone that is reserved for program use. Since main calls no other function, it has no need to move the stack pointer by more than it needs, though it doesn't matter in this case. It only subtracts enough from rsp to ensure that the array is protected by the red zone.

您可以通过向main

int test() {
  int arr[120];
  return arr[0]+arr[119];
}

int main() {
  int arr[120];
  test();
  return arr[0]+arr[119];
}

这给出了:

test:
  push rbp
  mov rbp, rsp
  sub rsp, 360
  mov edx, DWORD PTR [rbp-480]
  mov eax, DWORD PTR [rbp-4]
  add eax, edx
  leave
  ret
main:
  push rbp
  mov rbp, rsp
  sub rsp, 480
  mov eax, 0
  call test
  mov edx, DWORD PTR [rbp-480]
  mov eax, DWORD PTR [rbp-4]
  add eax, edx
  leave
  ret

您可以看到main函数减去480的原因是它需要将数组放在其堆栈空间中,而测试则不需要,因为它不调用任何函数.

You can see that the main function subtracts by 480 because it needs the array to be in its stack space, but test doesn't need to because it doesn't call any functions.

额外使用数组元素不会显着改变输出,但是添加该数组是为了清楚地表明,它并不假装这些元素不存在.

The additional usage of array elements does not significantly change the output, but it was added to make it clear that it's not pretending that those elements don't exist.

这篇关于为什么编译器会保留少量堆栈空间,而不保留整个数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆