Click here to Skip to main content
15,886,734 members

Response to: static memory allocates at compile time how?

Revision 1
For this answer i have compiled the information from different sources but mainly from Q&A of Stackoverflow.com.

A process has 5 different areas of memory allocated

1. Code - text segment
2. Initialized data – .data segment
3. Uninitialized data – .bss segment
4. Heap
5. Stack

+--------------------------+
| |
| command line |
| arguments |
| (argc and argv[]) |
| |
+--------------------------+
| Stack |
| (grows-downwards) |
| |
| |
| |
| F R E E |
| S P A C E |
| |
| |
| |
| |
| (grows upwards) Heap |
+--------------------------+
| |
| Initialized data |
| segment |
| |
+--------------------------+
| |
| Initialized to |
| Zero (BSS) |
| |
+--------------------------+
| |
| Program Code |
| |
+--------------------------+


In you case the answer is -
void main()
{
int x;\\on the stack, i.e. destroyed when main() returns
static int i;  \\stored in BSS
}


More general sample (see What is stored on heap and what is stored on stack?[^]) -
char * str = "Text line 1";  /* 1 */
char * buf0 ;                         /* 2 */

int main(){
    char * str2 = "Text line 2" ;  /* 3 */
    static char * str3 = str;         /* 4 */
    char * buf1 ;                     /* 5 */
    buf0 = malloc(BUFSIZ);            /* 6 */
    buf1 = malloc(BUFSIZ);            /* 7 */

    return 0;
} 


1.This is neither allocated on the stack NOR on the heap. Instead it's allocated as static data, and put into it's own memory segment on most modern machines. The actual string is also being allocated as static data, and put into a read-only segment in right-thinking machines.

2. Is simply a static alocated pointer; room for one address, in static data.

3. Has the pointer allocated on the stack, and will be effectively deallocated when main returns. The string, since it's a constant, is allocated in static data space along with the other strings.

4. Is actually allocated exactly like at 2. The static keyword tells you that it's not to be allocated on the stack.

5. But buf1 is on the stack, and

6. The malloc'ed buffer space is on the heap.
Posted 22-May-12 23:02pm by Sergey Chepurin.
Tags: , , ,