All questions I found on this site refer only to Stack vs Heap and don't
discuss Frame so here is my question. Don't get the difference between all three.
What I know:
Frame:
A frame is like a blackboard for instance variables of a function.
While the function is running all instance variables are stored
inside the frame of that function. When a function is called its
frame is created on top of the stack.
Stack:
A stack can be visualized as a physical stack of frames.
When a method (or function) is executed, it allocates a
chunk of memory from the stack.
Heap:
All object pointers live on the heap.
Stack and Frame is clear (I think) but am I right with my Heap statement?
Heap: All object pointers live on the heap.
Stack and Frame is clear (I think) but am I right with my Heap statement?
Not quite. Most(*) dynamically allocated objects live on the heap, the pointers to those objects live in other objects (or variables, they are essentially the same thing) - which may be on the stack or heap. This distinction between "objects" and "pointers to objects" is important in Objective-C (it is not so in all languages), and its not correct to say all "object pointers live on the heap".
(*) "Most" as it is possible, and sometimes quite useful, to allocate dynamic objects on the stack. You cannot do this with Objective-C objects, but you can do this with C objects (and C is part of Objective-C). Don't concern yourself yet with this, this footnote serves more to illustrate that the model being described here is a simplification.
Yes. Heap is noncontinuous space for dynamic memory.
Building on #CRD's answer...
Another way to think about the heap is as it's name implies - a messy pile. We need the pointers to help find our way back to the objects that have been tossed on the heap.
Related
I am taking a course on programming languages right now and am having trouble understanding the difference between stack and heap variables and why both are needed in a program.
My textbook says this about "stack-dynamic variables":
Stack-dynamic variables are those whose storage bindings are created when
their declaration statements are elaborated, but whose types are statically
bound. Elaboration of such a declaration refers to the storage allocation and
binding process indicated by the declaration, which takes place when
execution reaches the code to which the declaration is attached. Therefore,
elaboration occurs during run time.
It also says this about "explicit heap-dynamic variables"
Explicit heap-dynamic variables are nameless (abstract) memory cells that
are allocated and deallocated by explicit run-time instructions written by the
programmer. These variables, which are allocated from and deallocated to the
heap, can only be referenced through pointer or reference variables. The heap
is a collection of storage cells whose organization is highly disorganized due
to the unpredictability of its use.
So my question is: why do we have both? From what I've read it seems that both stack variables and heap variables are allocated at runtime, so other than the fact that you need to use special keywords like new in C++ to create heap variables, I'm having trouble understanding the difference. I know that certain data structures like trees and linked lists are created with heap variables, but why is it not possible to create them using stack variables?
Every time when I initiate a list in java, I will do
List<Integer> list = new LinkedList<>();
I assume that this will allocate the list on heap. Wonder if there's anyway that I could allocate the list on stack?
All objects, including their individual attributes, are stored on the heap.
All local variables, and their arguments, are stored on the stack because they contain primitive values or references.
However, in special cases, the java virtual machine may perform escape analysis and decide to allocate objects (including your LinkedList) on a stack, but this normally doesn't happen and isn't a major concern.
As a general rule, if you allocate an object on a stack you will get a copy of the object when you call a function that refers to it. In contrast, if you allocate an object on the heap, when you pass the pointer to the object you will get a copy of the pointer (which points to the very same object on the heap.)
It is theoretically possible for JVM implementations to allocate objects on the stack, using "escape analysis." If it can be determined that a reference to a created object never leaks off the stack, a JVM could allocate it on the stack instead of the heap. The benefit of this would be to reduce garbage collection overhead; when the stack frame is exited, that memory could be immediately reclaimed. It might also boost speed because of the locality of reference.
Starting in Java 7, escape analysis was introduced in the Oracle's HotSpot Java runtime. With this enhancement, HotSpot may choose not to allocate stack-local objects that aren't modified; rather than allocating them on the stack, it deletes the allocation altogether. While this stops short of stack allocation, it does demonstrate that such things are permissible runtime optimizations.
There is no way for the Java programmer to directly control this behavior, however. It's an optimization performed by the JIT compiler. I'm not sure if the language specification would permit this sort of optimization at compile-time. It might, but I haven't studied it.
I have read that stacks are using to manage function calls, where as heaps are used to store the objects that are allocating. What I understood that non primitive type objects will be stored in heap. I am confused on the following usages in the case of stack & heap:
1) Where the primitive data types, MACROS(#define), static objects, const, and extern?
2) Stacks manages the function calls, but I would like to know what info related to the functions are pushing to the stack?
3) I read somewhere that function related local objects are stored in Stack. So if any allocation of objects happens inside function, stack or heap is used? And if any primitive types objects are declared inside the function, where those are storing?
Sree.
Macros are resolved at compile time. Consts, globals, etc are part of the data segment - not the stack or the heap. https://en.wikipedia.org/wiki/Data_segment
Whenever you call a function it's parameters are pushed onto the stack.
All primitives, local variables, etc inside a function are allocated on the stack.
In simplified terms the compiler calculates how much memory each function needs (the total of all its variable usage). When the function is called that size is simply added to the stack and then it is subtracted in when it is finished.
At the most primitive level the only time heap memory is used (excluding libraries) is when you call malloc.
In the case of Objective-C pretty much every object is allocated dynamically on the heap whenever you call alloc or new. Objective-C is designed that way and heap allocation is normal. C and C++ tend to use the dynamic allocation on the heap less.
To understand what's really happening, you should build a small c program and generate assembly code of it.
What you will find there is the following:
Macros should be evaluated at compile time, not at runtime.
Constants, globals and static things are declared as constants and saved into the executable itself.
Primitive data variables or pointers are stored into CPU registers (extremely fast but limited in quantity) or stored in a stack frame in memory (more space but ca. 1000x slower). To understand stack frames, you should have a look at this explanation. Basically a stack frame is built by moving the stack pointer (which points to the memory location where new values are put onto the stack) down (the stack grows from big memory addresses to smaller ones) so there is some unused space on the stack, which can be locally used during a function.
If you call a function, the return address (the instruction pointer before the call + 1) is pushed onto the stack so when the function returns, the execution jumps to the return address by popping the return address from the stack and jumping to it.
If your function has a lot of arguments, the arguments 7, 8, etc... are stored on the stack before the function is called. All previous arguments are stored in registers
Unlike the stack, the heap space is assigned by the system and can only be accessed (to my knowledge) by interrupting the program and letting the operating system assign memory to the program (which will happen inside a malloc call). As objects are allocated ([NSObject alloc]) they can be found in the heap memory.
Summary
Primitive values and structs are stored next to return addresses of function calls on the stack
large memory allocations above a few bytes are made in heap space. This includes objects and arrays created with malloc.
I'm learning Objectiv C, and I hear the term "live in the heap" constantly, from what I understand its some kind of unknown area that a pointer lives in, but trying to really put head around the exact term...like "we should make our property strong so it won't live in the heap. He said that since the property is private. I know it'ss a big difference It's pretty clear that we want to make sure that we want to count the reference to this object so the autorelease wont clean it (we want to "retain" it from what i know so far), but I want to make sure I understand the term since it's being use pretty often.
Appreciate it
There are three major memory areas used by C (and by extension, Objective C) programs for storing the data:
The static area
The automatic area (also known as "the stack"), and
The dynamic area (also known as "the heap").
When you allocate objects by sending their class a new or alloc message, the resultant object is allocated in the dynamic storage area, so the object is said to live in the heap. All Objective-C objects are like that (although the pointers that reference these objects may be in any of the three memory data areas). In contrast, primitive local variables and arrays "live" on the stack, while global primitive variables and arrays live in the static data storage.
Only the heap objects are reference counted, although you can allocate memory from the heap using malloc/calloc/realloc, in which case the allocation would not be reference-counted: your code would be responsible for deciding when to free the allocated dynamic memory.
I am somewhat confused about when things are allocated on the heap (and I need to release them) and when they are allocated on the stack (and I don't need to relese them).
Is there a rule of thumb?
I think in C++ the rule of thumb is that if you use the new keyword they are on the heap. What is the rule with objective c? How can I tell when something is allocated on the stack?
Will this line of code be allocated on the stack?
NSString *user = #"DEFAULT";
Objective-C is easy in this regard.
All Objective-C Objects Are Always Allocated On The Heap.
Or, at the least, should be treated as if they are on the heap.
For:
NSString *user = #"DEFAULT";
The string object is not technically in the heap, but might as well be. Namely, it is generated by the compiler and is a part of your app's binary. It doesn't need to be retained and released because the class (NSCFConstantString, IIRC) overrides retain/release/autorelease to effectively do nothing.
As for when you do and don't release objects, you should read (and re-read) the Objective-C memory management guide.
(There is one other exception, but it is a rather esoteric detail; blocks start on the stack and you can Block_copy() them to the heap. Blocks also happen to be Objective-C objects, but that is rarely exposed in use.)
In Objective-C, it's easy: all objects are allocated on the heap.
The rule is, if you call a method with alloc or new or copy in the name (or you call retain), you own that object, and you must release it at some point later when you are done with it. There has been plenty written on the subject.
The example you give is a special case: that's a static string, I believe it is actually located in the program's data segment (on the heap), but it's static so you don't need to worry about releasing it.
There are no stack allocations of objects in Objective-C (Blocks are a different case that I'm not going to get into here)
NSString *user = #"DEFAULT";
That allocates a NSConstantString object in constant memory, not on the stack.
In Objective-C (and many other languages), an object is simply a contiguous blob of memory with a particular layout. Objects are usually created on the heap. The storage for the object pointer variable itself is on the stack
but the object it points to is in the heap.