I encountered the following question in an exam:
When a program calls a function, in which type of data structure is
the memory allocated for the variable in that function?
- HEAP
- QUEUE
- LIFO
- STACK
According to the test, HEAP is the correct answer, although I selected STACK.
Can someone fantastic person out there please explain why?
Thanks in advance.
Well, local variables and parameters are stored on the stack not on a heap. For local value-types, this means that the value itself is stored on the stack. For local reference-types, only the reference will be on the stack.
Yet to get a more in-depth explanation I recommend to read a very good blog post of Erik Lippert's (who has already pointed to this blog post in the comment): The Stack Is An Implementation Detail, Part One .
First, C# doesn't have "functions"; it has "methods".
What do you mean by "in which type of data structure is the memory allocated for the variable in that function?"
Nota Bene: Just for the record, "LIFO" is an access strategy (Last-In, First-Out),
not a data structure. Normally, one refers to a STACK as a LIFO STACK. But I digress.
The correct answer is, usually, either
- "it depends", or
- "both stack and heap"
Slots for local variables (variables that only exist within the context of a method invocation) are allocated within the stack frame for the duration of the method invocation, which is located in the program stack.
If the variable is a reference type, that slot is a reference to the actual object instance, memory for which will be allocated from the heap when/if it is instantiated.
IF the variable is a value type, that slot is [usually, but not always] the object instance itself . . . but that is not a given. Value types can (and are), if need be, allocated on the heap. In which case, the stack frame slot for the variable is, like a value type, a reference to the instance allocated on the heap.
This is a very poorly written question, and I wonder about the abilities of the person who wrote it. As bejger answered, in most languages local variables (and function arguments) are stored on "the stack." In reference languages like C# or Java, objects are stored in "the heap" with a reference to the object (a pointer) stored on the "stack." The question is suspect because it doesn't specify the language or the exact scenario. Also, I wouldn't call the heap and the stack "data structures" at all. They're memory allocation schemes, not data structures in this context.