Clarification on stack & heap
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:
[NSObject alloc]
) they can be found in the heap memory. Summary
上一篇: Permgen是否是堆的一部分?
下一篇: 澄清堆栈和堆