简体   繁体   中英

Want to understand how function variables are stored in stack

I am trying to understand how variables are stored in the memory stack and what the printf statements are printing. Your insight in this will be highly appreciated. Thank you.

Ideone link http://ideone.com/uWvPpX

#include <stdio.h>

int main(void) {

    foo("%x");
    return 0;
}

void foo(char *str)
{

    char c='c';
    printf(str);

    printf("\n%x",&c);
}

%x is a format specifier indicates you want to print in lower-case hexadecimal. So when you don't specify data in the first printf the result is undefined. Even though the code compiles - it is incomplete!

So let us fix the code first- here is the revised code

#include <stdio.h>

void foo(char *str);

int main(int argc, char* argv[])
{

    foo("%x");
    return 0;
}

void foo(char *str)
{

    char c='c';
    printf(str,c);

    printf("\n%x",&c);
}

Now to answer your questions "how variables are stored in the memory stack" The stack pointer registers the top of the stack,every time a value is pushed on to or popped out of the stack - the stack pointer is adjusted to point to the free memory. And then there is the stack frame, it corresponds to a call to the function which has not yet terminated with a return. 在此处输入图片说明

the other part was "what the printf statements are printing." The first parameter in the printf is a format specifier, the second parameter onwards are the data that are to be used for those format specifier(s). When you did not have the c in your first original printf - it just picked up the adjacent int and printed that for %x that was specified. In the revised first printf I made it print he cvalue of c in hexadecimal. In your second printf you make it print the address of C variable that is in the stack.

Check these links for further details - https://en.wikipedia.org/wiki/Call_stack#Structure Also other Stackoverflow Q&As that show up on the right pane.

TO 8086 platforms: As you can read here , stack is the runtime/call stack, each function local vars are stored in the current procedure stack frame. read more about runtime/call stack here

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