简体   繁体   中英

Where are static variables stored (data segment or heap or BSS)?

I obtained conflicting Opinions about static variable storage.

Opinion 1 : "A stack static variable stores its value in the heap "

Opinion 2 : "A stack static variable stores its value in the data segment".

I am confused with these conflicting answers.

Where exactly are static variables stored?

I am expecting an answers with references (text books, authentic tutorials, etc.).

Static variables have two types:

  1. static variables declared inside a function.
  2. global (declared outside function) static variable.

I would also like to know if there is any difference in the storage of these two types of variables?

The 'stack variables' are usually stored on 'the stack', which is separate from the text, data, bss and heap sections of your program.

The second half of your question is about 'static' variables, which are different from stack variables - indeed, static variables do not live on the stack at all. Classically, static variables would all be in the data or bss sections of your program. With modern compilers, if the data is const-qualified, then the data may be stored in the text section of your program, which has a variety of benefits (including enforced non-modifiability).

The C standard does not dictate that there is a stack, nor a bss section. It just requires storage space to be available for variables with appropriate durations.

Stack memory is allocated when you launch your application and always remains the same size during the execution of the application. It's not stored in the DATA segment, DATA segment is for things like constant values used in the application (such as string literals).

Both local and global static variables are kept in initialized Data segments

There are two data segments initialized data segment and unitialized data segment.

Unitialized data segment also called BSS.

When we say data segment, by default it initialized data segment, this section gets copied from loaded image of the program. ( all global variables and local static variables initialized to to non zero ie ini var1_global = 10; )

The uninitialized data segemnet aka BSS. This section will be initialized to zero generall, just before main() gets called. All unitialized global, local static goes here.

http://www.geeksforgeeks.org/memory-layout-of-c-program/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM