简体   繁体   中英

Organisation of data on the stack in C?

I am learning C language and have some questions. When we declare a variable such as int i = 0 . the i has the address in stack, right?

I am wondering how a function is organized in memory. For instance, I have a function as:

int myF() {
  int x = 2, y = 3;
  int z = x + y;
  return x;
}

How is this method organized in the stack? I mean the name " myF " has a memory address too like other varialbes? And " myF " should have something like ending address to indicate where is the end of the function?

Am I wrong?

Thanks a lot.

Usually the code of the function is stored separately in read-only memory segment and the stack ("automatic storage") is not overlapping with that. Also the name myF is eliminated during compilation and the function becomes just a piece of code starting at some address and ending with a special processor instruction meaning "return from current function".

A diagram will help show how it is organized:

Stack layout

  • Local variables (like i in your example) may be on the stack, but it depends on the compiler. A typical stack layout will show the local variables area but, for example, some compilers may use a register for a variable instead.
  • The name myF does not have an address, but the function does. The address will generally be in a separate area of executable code.
  • There is not an 'ending address' - instead a return address is saved by the calling function. When myF reaches the end of the function and is performing any cleanup operations, it will then branch to the return address. This can actually be an issue because there are some exploits which seek to change this return address and cause the code to branch to malicious code to be executed.

The i has the address in stack, right?

Not necessarily.

How is this method organized in the stack?

The answer is it depends on the compiler and processor architecture. Some compilers store local variables on the stack. Others will use registers.

Check out this question scope of variables for more discussion.

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