8

Yesterday I had an interview where the interviewer asked me about the storage classes where variables are stored.

My answer war:

Local Variables are stored in Stack.       
Register variables are stored in Register
Global & static variables are stored in data segment.  
The memory created dynamically are stored in Heap.

The next question he asked me was: why are they getting stored in those specific memory area? Why is the Local variable not getting stored in register (though I need an auto variable getting used very frequently in my program)? Or why global or static variables are not getting stored in stack?

Then I was clueless. Please help me.

pb2q
  • 58,613
  • 19
  • 146
  • 147
Rasmi Ranjan Nayak
  • 11,510
  • 29
  • 82
  • 122
  • 4
    `register` variables may not be stored in a register. – user703016 May 25 '12 at 06:18
  • Local variables are not always stored in the stack (are often elided or moved to registers). Register variables are not always stored in registers (they are often moved to the stack). Global (including static) variables are not always stored in the data segment (they are often placed in the text segment, or in dedicated memory maps). The only difference between a register variable and a non-register local is that the compiler rejects programs that take the address of a register variable. – Dietrich Epp May 25 '12 at 06:18

5 Answers5

16

Because the storage area determines the scope and the lifetime of the variables.

You choose a storage specification depending on your requirement, i.e:
Lifetime: The duration you expect the particular variable needs to be alive and valid.
Scope: The scope(areas) where you expect the variable to be accessible.

In short, each storage area provides a different functionality and you need various functionality hence different storage areas.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • :If that is the case when we declare a variable `fun(){static int a; a++;}` then I am going other function (suppose `fun2`)and then I am coming back to `fun()` how a retains its previous value. because lifetime of `static` is inside the `fun()` – Rasmi Ranjan Nayak May 25 '12 at 06:25
  • I do not understend this answer. There is no such thing as scope and lifetime in microprocessor.There is just some contiguous memory area an somewhere in this area is LIFO (stack). – Luka Rahne May 25 '12 at 06:30
  • @RasmiRanjanNayak: Yes,that is the whole point of it.You want a variable `a` in a function be alive throughout the lifetime of the program, so you choose the `static` storage class, It doesn't matter where the compiler stores this variable, the standard doesn't really say anything about it and it is a implementation detail, but the standard mandates a `static` variable to be alive throughout the lifetime and maintain its state. – Alok Save May 25 '12 at 06:33
  • @ralu: *Scope* and *lifetime* are associated with storage specifications the c/c++ standard provides through keywords,`static`, `extern`, `register` etc.The standard mandates that when you use these keywords on a variable declaration the implementation should ensure certain scope and lifetime attributes to that variable.The standard does not say ***how*** or ***where*** these variables be saved or how the functionality should be implemented.That is an implementation detail. It only mandates the user should get the attributes associated to the particualr storage class. – Alok Save May 25 '12 at 06:39
  • @ralu, programming languages such as C provide you with an abstraction of a platform and the compiled program is guaranteed to have a certain observable behavior that realizes this abstraction. If you don't want that you'd have to program in assembler that implements exactly the features of the specific processor your programming for. – Jens Gustedt May 25 '12 at 06:40
  • Question is about where are such variables stored and you are talking about lifetime and scope. Talking this way is just like, because standard said so. I Haven't read standard, but looks like it does not talk about stack and heap so you can not explain them using scope and lifetime. – Luka Rahne May 25 '12 at 07:01
  • @Als, `register` does not actually mandate anything _whatsoever_. It's just a hint. – bdonlan May 25 '12 at 07:18
  • @bdonlan: Well spotted. `register` being in that list was a typo.Indeed [`register` does not mandate anything](http://stackoverflow.com/a/6167818/452307). – Alok Save May 25 '12 at 08:05
14

The C language does not define where any variables are stored, actually. It does, however, define three storage classes: static, automatic, and dynamic.

Static variables are created during program initialization (prior to main()) and remain in existence until program termination. File-scope ('global') and static variables fall under the category. While these commonly are stored in the data segment, the C standard does not require this to be the case, and in some cases (eg, C interpreters) they may be stored in other locations, such as the heap.

Automatic variables are local variables declared in a function body. They are created when or before program flow reaches their declaration, and destroyed when they go out of scope; new instances of these variables are created for recursive function invocations. A stack is a convenient way to implement these variables, but again, it is not required. You could implement automatics in the heap as well, if you chose, and they're commonly placed in registers as well. In many cases, an automatic variable will move between the stack and heap during its lifetime.

Note that the register annotation for automatic variables is a hint - the compiler is not obligated to do anything with it, and indeed many modern compilers ignore it completely.

Finally, dynamic objects (there is no such thing as a dynamic variable in C) refer to values created explicitly using malloc, calloc or other similar allocation functions. They come into existence when explicitly created, and are destroyed when explicitly freed. A heap is a convenient place to put these - or rather, one defines a heap based on the ability to do this style of allocation. But again, the compiler implementation is free to do whatever it wants. If the compiler can perform static analysis to determine the lifetime of a dynamic object, it might be able to move it to the data segment or stack (however, few C compilers do this sort of 'escape analysis').

The key takeaway here is that the C language standard only defines how long a given value is in existence for. And a minimum bound for this lifetime at that - it may remain longer than is required. Exactly how to place this in memory is a subject in which the language and library implementation is given significant freedom.

bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • Hey @bdonlan, I answered same in an Interview that Statics are stored on Heap. The Interviewer was like "You are Wrong.... Have You ever reffered to K&R and blah blah"... So was my answer wrong? What's it according to K&R? – Swanand Jun 18 '12 at 12:39
  • @SwanandPurankar, K&R is out of date. It's a good conceptual guide, though, or so I hear, but if you want to be technically correct on things like this it's better to refer to the actual spec. The C language specification does not talk about the 'heap'. Whether to put something on the heap or not is a choice of the implementation. However, most implementations do not put statics on the heap (there are rare exceptions, such as C interpreters, however). – bdonlan Jun 20 '12 at 02:43
1

It is actually just an implementation detail that is convenient.

The compiler could, if he wanted to, generate local variables on the heap if he wishes.

It is just easier to create them on the stack since when leaving a function you can adjust the frame pointer with a simple add/subtract depending on the growth direction of the stack and so automatically free the used space for the next function. Creating locals on the heap however would mean more house-keeping work.

Another point is local variables must not be created on the stack, they can be stored and used just in a register if the compiler thinks that's more appropriate and has enough registers to do so.

RedX
  • 14,749
  • 1
  • 53
  • 76
0

Local variables are stored in registers in most cases, because registers are pushed and poped from stack when you make function calls It looks like they are on stack.

There is actually no such tings as register variables because it is just some rarely used keyword in C that tells compiler to try to put this in registers. I think that most compilers just ignore this keyword.

That why asked you more, because he was not sure if you deeply understand topic. Fact is that register variables are virtually on stack.

Luka Rahne
  • 10,336
  • 3
  • 34
  • 56
  • `register` is not useless it means `auto` plus interdiction of taking the address of the variable. So this is an optimization hint just as `restrict` for pointer parameters, e.g. – Jens Gustedt May 25 '12 at 06:35
  • Most variables goes in register by default. register can be used only to tell compiler that such variable has priority for going in register. – Luka Rahne May 25 '12 at 06:42
  • you are mixing to different concepts. Registers of the processor and the `register` keyword of the C language. I was just saying what the language keyword specifies, it has not much to do with the fact that a variable is realized in a register (of the processor) or not. If you want it is just a misnomer, replace `register` (the keyword) by `addressless` and you are closer to what it means in C. – Jens Gustedt May 25 '12 at 08:49
  • "registers are pushed...when you make function calls" - some are, others may hold function arguments, others may only be pushed by the called function if it feels it needs more registers, and in some cases CPUs support their own mechanisms for saving and restoring registers sans stack (e.g. UltraSparcs). Also, it's not uncommon to have local arrays and textual data - they're unlikely to fit in registers, so "local...in registers in most cases" without clarification's not providing insight. Then "register variables are virtually on stack" - after saying non-`register` vars were in registers! – Tony Delroy May 29 '12 at 15:58
0

in embedded systems we have different types of memories(read only non volatile(ROM), read write non volatile(EEPROM, PROM, SRAM, NVRAM, flash), volatile(RAM)) to use and also we have different requirements(cannot change and also persist after power cycling, can change and also persist after power cycling, can change any time) on data we have. we have different sections because we have to map our requirements of data to different types of available memories optimistically.