Google Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Great answer. Also accessing memory on stack seems to be faster because of high memory locality.
Garbage collector works in two passes.
1. The system goes through the memory area and marks all the pointers which are pointing to the allocated memory.
2. Then it runs through all the unmarked memory area and declare them as free.
Physically stack and heap both are allocated on RAM and their implementation varies from language, compiler and run time
- Vijay March 29, 2013Stack is used for local variables of functions and to track function calling sequences. Heap is used for allocating dynamically created variables using malloc, calloc or new.
Stack memory is freed whenever the function completes execution but the heap memory needs to be freed explicitly using delete, free or by garbage collector of the language.
Stack memory of a process is fixed size and heap is variable memory.
Stack is faster than heap as allocating memory on stack is simpler just moving stack pointer up.
In case of multi threading, each thread of process will have a different stack but all threads share single heap