What is BSS Segment in C: Explanation and Example
BSS segment in C is a part of a program's memory that stores uninitialized global and static variables. It holds variables that start with zero or no specific value and is allocated at runtime before the program starts running.How It Works
Imagine your program's memory as a house with different rooms. The BSS segment is like a storage room where all uninitialized global and static variables are kept. These variables don't have a set value when the program starts, so the system sets them to zero automatically.
When you declare a global or static variable without giving it a value, the compiler places it in the BSS segment. This helps save space because the BSS segment only stores the size of these variables, not their actual values, since they are zero by default. This is different from initialized variables, which go into a different memory area called the data segment.
Example
This example shows a global uninitialized variable stored in the BSS segment. It prints the default value zero.
#include <stdio.h> static int count; // uninitialized static variable int main() { printf("Value of count: %d\n", count); return 0; }
When to Use
Use the BSS segment automatically by declaring global or static variables without initializing them. This is useful when you want variables to start at zero without wasting space in your program file.
For example, counters, flags, or buffers that you want to clear at program start can be declared this way. It helps keep your program efficient because the BSS segment does not take up space in the executable file for initial values.
Key Points
- The BSS segment stores uninitialized global and static variables.
- Variables in BSS are automatically set to zero before the program runs.
- It helps reduce the size of the executable file.
- Initialized variables go to the data segment, not BSS.