2

i ran into a question i didnt know the answer to so i am posting here :) does a static variable defined (not initialized) on the start of the program or when i enter the function it is defined in?

i know that the initialization of the static variable happens in the function it is defined, but i am not talking about initialization but definition, when it takes sapce in my stoarge.

i found out it is always in a lower address than the local variable in the main? is it related? is the variables always lower in the address if they are defined before? thanks for the answers

  • 4
    I'm farily certain this is a implementation detail. IIRC the standard only states that function local statics lifetime begins when the initialization is first reached. – NathanOliver Mar 30 '17 at 18:23
  • 1
    Possible duplicate of [What is the lifetime of a static variable in a C++ function?](http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function) – soulsabr Mar 30 '17 at 18:41
  • @NathanOliver: If the memory organisation cited in http://stackoverflow.com/a/11698458/2630032 is correct, then non-initialized static variables reside in bss (and before the heap), right?. Hence, if it is about the time of allocation (not lifetime of the variable and not initialization itself), then static non-initialized variables are still "lower" than all others, right? – Stephan Lechner Mar 30 '17 at 18:41
  • @StephanLechner Maybe. The accepted answer there says it could be in the DATA section though. – NathanOliver Mar 30 '17 at 18:45

1 Answers1

2

Please consider the memory layout of a typical C/C++ program, for instance, from CS-fundamentals.com.

enter image description here

The place for extern variables (from other modules), global and static variables is called uninitialized data segment (or bss). Since the program can't guess what functions will be called, it is reasonable to believe that all the static variables that are local in scope will have its place defined there in the start of the program.

And local variables (the ones that disappear when you leave a function) are kept in the stack area.

That's almost everything we can know about the placement of memory variables. Anything else is largely dependent on the decision of the author of the code generation step of the compilation process.

Hilton Fernandes
  • 559
  • 6
  • 11