Stack vs Heap
Har C program ke paas do main memory areas hote hain: Stack (local variables, function calls — automatically manage hota hai, bahut fast, lekin limited size) aur Heap (dynamically allocated memory — tum khud control karte ho, bada size, lekin thoda slow aur manual management chahiye).
Stack "LIFO" (Last In First Out) tarike se kaam karta hai — jab function call hota hai, uski local variables stack par push hoti hain, function khatam hote hi automatically pop ho jaati hain. Heap mein memory tab tak rehti hai jab tak tum khud usse free() na karo — isliye "memory leaks" sirf heap mein hote hain, stack mein nahi.
Stack overflow tab hota hai jab bahut zyada nested function calls (jaise infinite recursion) stack ki fixed size se zyada memory maang le. Heap mein aisi koi automatic limit nahi hoti (RAM ki limit tak grow kar sakta hai).
void func() {
int local = 10; // stack par — function khatam hote hi gayab
int *heapVar = malloc(sizeof(int)); // heap par — manually free() karna padega
*heapVar = 20;
free(heapVar); // zaroori — warna memory leak
}- Stack = automatic, fast, fixed size, LIFO
- Heap = manual (malloc/free), bada, flexible
- Stack overflow = bahut zyada nested calls; heap leak = free() bhoolna
Stack overflow tab hota hai jab function calls itni deep nest ho jaayein (usually infinite ya bahut deep recursion) ki stack ki fixed memory khatam ho jaaye. Operating system ek crash ("segmentation fault") ke saath program ko rok deta hai.
Har recursive call apni local variables ke liye naya stack frame banata hai — agar base case kabhi na mile (ya bahut door ho), stack frames ka dher operating system ki di hui limit (typically kuch MB) se aage nikal jaata hai.
int badRecursion(int n) {
return badRecursion(n + 1); // koi base case nahi — infinite recursion
}
int main() {
badRecursion(0); // Segmentation fault (stack overflow)
return 0;
}Teen tarah ki variable lifetimes hoti hain C mein: automatic (stack — function ke andar declare hui normal variables, function khatam hote hi gayab), dynamic (heap — malloc se, tab tak zinda jab tak free() na ho), aur static (poori program lifetime tak zinda, chahe global ho ya static keyword wali local variable).
int global = 1; // static lifetime — poore program tak
void func() {
int local = 2; // automatic (stack) — func khatam hote hi gayab
static int counter = 0; // static — value function calls ke beech preserve hoti hai
int *heapVar = malloc(4); // dynamic (heap) — jab tak free() na ho
counter++;
printf("%d\n", counter); // har call par badhta jaata hai
free(heapVar);
}