0

I mean does the program use the hardware directly to push a local variable onto a stack or does it has to call a OS library to do that?

BTW for linux, In the code below, when compiling, is '6' stored in any ELF section similiar to .data/.text section? And when 'func' is invoked, is CPU fetching '6' from any section and push it onto the stack?

func(){
  int a = 6;
}
Camelid
  • 1,535
  • 8
  • 21
郑嘉诚
  • 1
  • 2

1 Answers1

2

Stacks are unique to each process running on a CPU, and the OS does not manage them. A program is free to use its stack however it likes.

So the answer to your first question is: no, the program pushes to the stack without OS intervention. In fact, pushing and popping the stack is such a common operation that many CPU architectures have dedicated instructions to do just that. You would not want to have to make a call into the OS every time you wanted to use the stack, that would add a mind-boggling amount of overhead to execution.

As to the second part of your question: All local variables are stored on the stack, not in an ELF section or other global memory. In fact, the entire purpose of the stack is to store local variables. When a local variable, one that is on the stack, is used, its value is fetched from memory just like any other. The stack is not some special memory or anything, it's just a piece of normal RAM that a program happens to be using as the stack. Now, that being said, the memory used for the stack itself is assigned to the program by the OS. But the memory itself? Nothing special about it.

You should take a look at this answer for further reading: How does the stack work in assembly language?

dykeag
  • 554
  • 3
  • 11
  • 2
    I think it's more accurate to say that local variables *can* be stored on the stack, rather than "are stored on the stack". Of course they are typically stored on the stack, but the language doesn't dictate that. – jarmod Oct 07 '20 at 16:55
  • Stacks are unique to each thread, running on a CPU core or not. – Martin James Oct 08 '20 at 05:23
  • When we want to push a local variable onto the stack, i.e. the local variable has not been on the stack yet, where does the CPU fetch this local variable's value? Is it an ELF section? – 郑嘉诚 Oct 08 '20 at 06:14
  • @郑嘉诚, are you asking about initialization values? For example, when you write something like: int x = 10; In that case, the value 10 can be stored in a few different ways. Small values can be stored directly in the instruction being used to set the value, or it can be stored in an ELF section, yes. – dykeag Oct 08 '20 at 18:26