简体   繁体   English

程序如何在这里使用堆栈?

[英]How is the program using the stack here?

For the code shown below, If I print the addresses, I get the following. 对于下面显示的代码,如果我打印地址,我会得到以下内容。

&test_var1 = 0x7fff0067d87c
&barrier (passed argument) = 0x7fff0067d770
&i (passed argument) = 0x7fff0067d77c
&test_var2 = 0x7fff0067d78c

There are two things I don't understand here. 这里有两件事我不明白。 First is that I read that C pushes arguments from right to left, then how &i is greater than &barrier . 首先是我读到C从右到左推动参数,然后是&i大于和障碍 Knowing that stack grows from a higher address to a lower address, &i should be at a lower address. 知道堆栈从较高地址增长到较低地址, &i应该位于较低地址。 Moreover, the local variable test_var2 is at even a greater address. 而且,局部变量test_var2甚至更大的地址。

Secondly, one would expect the value of &barrier and &test_var1 to be close together, but no, you see a big difference of 268 bytes. 其次,人们会期望&barrier&test_var1的值靠得很近,但不会,你会看到268字节的巨大差异。 What is the stack holding in between? 两者之间的堆栈是什么?

Note that I'm using optimization O3. 请注意,我正在使用优化O3。 Is this due to that? 这是由于那个吗? Maybe the compiler has played some tricks here? 也许编译器在这里玩了一些技巧? I use volatile to make sure every variable is on the stack here and not cached in some register. 我使用volatile来确保每个变量都在堆栈中,而不是缓存在某个寄存器中。

void some_func()
{
.........
{
  volatile int test_var1 = 0;
}
call_func( i, &barrier );
........
}

void call_func( volatile int i, volatile pthread_barrier* barrier )
{
 volatile int test_var2 = 0;
 ........
}

On x86 the stack (used when f() calls g()) grows downward. 在x86上,堆栈(当f()调用g()时使用)向下增长。

Anyhow the way the compiler arranges the var/s for a certain call is implementation dependend. 无论如何,编译器为某个调用安排var / s的方式是实现依赖。

You're making a bunch of assumptions here, none of which are really warranted: 你在这里做了一堆假设,其中没有一个是真的有理由:

  • The compiler has to push some number of registers when it calls a function; 编译器调用函数时必须推送一些寄存器; there's no rule that says they can't be in between the arguments and the local variables. 没有规则说它们不能介于参数和局部变量之间。
  • There's no rule that the arguments have to be pushed in any particular order, or event that they are on the stack at all; 没有规则必须以任何特定的顺序推送参数,或者根本不存在它们在堆栈中的事件; arguments can be passed in registers, too. 参数也可以在寄存器中传递。
  • How memory is organized into a program stack is processor-dependent; 内存如何组织成程序堆栈取决于处理器; in the x86 architecture it grows downward , not upwards. 在x86架构中,它向下增长,而不是向上增长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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