----- Original Message ----- From: "Girish BR"To: Sent: Thursday, June 17, 2004 6:10 PM Subject: [UTTARA] Static Variable > Why is a static variable stored in a Heap?? This is a VERY general assumption you have made that the static variables are stored in the heap. As far as I know, they are stored in the data section of the process. Here is an approximate picture: ____________ | Stack | (Stack grows downwards) |............| | | | | | | |............| | Heap | (Heap grows upwards) ------------ | Static | (also called data-section) ------------ | Constants | ------------ | Text | ------------ The C programming language defines 3 storage types: automatic, static and allocated. + Automatic(local) variables can be stored in the machine registers and stack. The stack is also used for function calls. + Global variables, and/or variables defined with the static storage speicifier, go to the static storage. (See the above diagram) + The heap is used for the `allocated' type of storage. When a request is made using either of malloc() or calloc() functions, storage is allocated from the heap. free() is used to return the memory back to the heap. Now, please check if your assumptions match with this or not. > What will happen if it is stored in a stack. If we go by what I have written above, static variables will not be stored in the stack. There are few reasons, however, as why they can not (in fact, should not) be stored in the stack. + Stack is a pretty dynamic entity. A variable stored once in the stack is not required to get the same logical address the next time. This is quite OK for an automatic variable. + On the other hand, an object of static storage type is allocated the storage at the program start up. Also note that a static object MUST have a fixed address through out the program execution. A stack can not guarantee this behaviour. This is why static variables are not stored in the stack. It must also be noted that the C Standard does not provide implementation details (like algorithms etc). It only talks about the behaviour and properties of the C language and it's constructs. An implementor is free to choose whatever mechanism (i.e., data-structures, etc.) that suits his purpose, but is required to meet all or most of the standard specifications. So, as a programmer we have the least to bother as where a static variable will go!
Text file Source (historic): geocities.com/vijoeyz/faq/c
geocities.com/vijoeyz/faqgeocities.com/vijoeyz
(to report bad content: archivehelp @ gmail)
|
|
|
|
|