Bloomberg LP Interview Question
Software Engineer / DevelopersStack:
- local variables (variables declared inside a function) are put on the stack - unless they are also declared as 'static' or 'register'
- function parameters are allocated on the stack
- local variables that are declared on the stack are not automatically initialized by the system so they usually have garbage in them until you set them
- variables on the stack disappear when the function exits (thus, if a function is called multiple times, it's local variables and parameters are recreated and destroyed each time the function is called end exited).
Heap:
- declared variables (as opposed to dynamically created ie new, malloc) are created on the heap before program execution begins, they exist the entire life of the program (although scope may prevent access to them - they still exist) and they are initialized to all zeros
- global variables are on the heap
- static local variables are on the heap (this is how they keep their value between function calls)
- memory allocated by new, malloc and calloc are on the heap
"Referenced document"
by declared variable on heap , do you refer to
int i=10 in the main function ?
main()
{
int i=10;
}
I feel any variable decalred within a function goes to stack .here int i=10 goes to stack and if its outside main and decalred globally , it goes to heap.please correct me If i am wrong.
No only dynamically allocated variables will be on heap. In this case, int i=0 is a global variable. This will be in the initialized data section.
Any process address space have following segments.
1. Stack Segment - Automatic variables or local varibles
2. Heap - Dynamically allocated variables
3. Code Segment
4. Data Segment
- Unintialized Data (bss) - Static variables (before program initializes, these variables will be initialized zero.
- initilaized Data (your int i =0)
Initialized data – data segment
Statically allocated and global data that are initialized with nonzero values live in the data segment. Each process running the same program has its own data segment. The portion of the executable file containing the data segment is the data section.
Uninitialized data – bss segment
BSS stands for ‘Block Started by Symbol’. Global and statically allocated data that initialized to zero by default are kept in what is called the BSS area of the process. Each process running the same program has its own BSS area. When running, the BSS, data are placed in the data segment. In the executable file, they are stored in the BSS section. For Linux/Unix the format of an executable, only variables that are initialized to a nonzero value occupy space in the executable’s disk file.
It's in the data segment of the code
- Anonymous April 13, 2010