how do compilers assign memory addresses to variables?

后端 未结 4 1339
你的背包
你的背包 2020-12-07 14:57

I teach a course where students get to ask questions about programming (!): I got this question:

Why does the machine choose were variables go in memo

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 15:49

    I think the answer to this question starts with an understanding of the layout of a program in memory. Underneath the operating system, a computer's main memory is just a giant array. When you run a program, the operating system will take a chunk of this memory and break it up into logical sections for the following purposes:

    • stack: this area of memory stores information about all functions currently in scope, including the currently running function and all of its ancestors. Information stored includes local variables and the address to return to when the function is done.

    • heap: this area of memory is used when you want to dynamically allocate some storage. Generally your local variable would then contain an address (ie, it would be a pointer) in the heap where your data is stored, and you could publish this address to other parts of your program without worrying that your data will be overwritten when the current function goes out of scope.

    • data, bss, text segments: these are more or less outside the scope of this particular question, but they store things such as global data and the program itself.

    Hope that helps. There are lots of good resources online as well. I just googled "layout of a program in memory" and found this one: http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory

提交回复
热议问题