How stack memory works or how function variables are allocated and accessible on the stack

5 answers

The stack pointer, like its name, has a pointer, like any other, and points to normal standard memory. To access any area of ​​the stack, simply add an offset to the pointer.

If you think about it in terms of C pointers, you have a stack pointer

char *stack_pointer = some_memory;

This pointer can then be used as a regular pointer, including adding offsets to access specific places on the stack, for example,

*(int *)(stack_pointer + 4) = 5;

I recommend that you try to find out the assembler code, then you can make a very simple program with several local variables and compile it into assembler code and read it to see exactly how it works.

+7
source

stack semantics vs stack region ( ). . , " , JVM CLR", , C ++, , .

:

  • - . C ++ Java/CLR.
  • " " " " -

O(1). - + , x86. LIFO, random accessible, O(1). , , .

LIFO. / ().

, , C ++ .

+4

. , "". . (, std::stack ++ STL), .

, ( ), , . "" , .

+2

, :

-

,

-

,

-

,

-

,

. ( ) , . . C. , . C, C.

+2

, , .

, , " " , , . :

main() foo(). main() EBP . main() . , . foo() ( ) , , " ", ESP, , main() " ", EIP, , . foo() main(), :

[ foo().]

[ foo().]

[main() . EBP , foo().]

[main() (foo() , .)]

[ foo().]

[ main().]

[...]

, foo(), , EBP. 4 , EBP-4, .

+1

All Articles