Lesson 13 — Advanced
Dynamic Memory Allocation
int a[100] likh diya aur user ko 5 chahiye? Size compile time pe fix — ye static allocation hai. Dynamic memory ka matlab hai: program chalte waqt, jitna chahiye utna lo (malloc), aur kaam ho toh wapas de do (free). Is lesson mein hum heap ka poora khel samjhenge.
Stack vs Heap — do duniya
WHAT
Dynamic allocation = runtime pe heap memory lena. malloc/calloc memory dete hain (address return), free wapas deta hai. Sab kuch heap pe hota hai jahan tum control lo — par zimmedaari bhi tumhari (free karna).
WHEN
Size runtime pata ho (user se input), data bada ho (array of records), ya lifetime function se lambi ho — tab dynamic. Function return ke baad bhi heap block zinda rehta hai.
WHERE
Har bade program mein — linked lists, trees, databases, buffers. DSA ka har structure isi se banta hai. Tumhara compiler bhi heap use karta hai.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = (int *)malloc(sizeof(int)); // 4 bytes heap pe
*p = 42;
printf("Value = %d\n", *p);
free(p); // wapas kar do!
return 0;
}
Output: Value = 42
- Stack: variables jo function ke — automatic, chhoti, fast, function return pe gayi. int a[100] bhi stack pe.
- Heap: malloc se mili — tumhari marzi, badi, dheemi thodi, free tum karte ho.
- stdlib.h: malloc, calloc, realloc, free — sab isi header mein.
- malloc return: void* — isliye cast (int *) karna padta hai (C mein style, C++ mein zaroori).
malloc vs calloc — garbage vs zero
malloc(size) : ek block, JUNK value (garbage)
calloc(count, size) : count * size bytes, SAB ZERO
realloc(ptr, newsize) : purane block ka size badalta hai
free(ptr) : block wapas — koi return value nahi
malloc(sizeof(int)) : 1 junks
calloc(5, sizeof(int)) : 0 0 0 0 0
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Kitne numbers? ");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int)); // garbage
int *arr2 = (int *)calloc(n, sizeof(int)); // 0
for (int i = 0; i < n; i++) arr[i] = (i + 1) * 10;
int sum = 0;
for (int i = 0; i < n; i++) sum += arr[i];
printf("Sum = %d\n", sum);
free(arr); free(arr2);
return 0;
}
Kitne numbers? 4
Output: Sum = 100
realloc — size badhao, free — wapas karo
#include <stdio.h>
#include <stdlib.h>
int main() {
int *a = (int *)malloc(2 * sizeof(int));
a[0] = 10; a[1] = 20;
// Ab 2 jagah chahiye thi, 4 chahiye — grow karo
a = (int *)realloc(a, 4 * sizeof(int));
a[2] = 30; a[3] = 40;
int sum = 0;
for (int i = 0; i < 4; i++) sum += a[i];
printf("Sum = %d\n", sum);
free(a);
return 0;
}
Output: Sum = 100
- realloc fail: NULL return ho sakta hai — aur usme pura purana pointer kho jaata hai. Safe pattern: temp = realloc(ptr, n); agar temp != NULL tab ptr = temp.
- Purana data bachta hai: realloc naye size tak copy kar deta hai (jitna purana tha).
- free ka rule: jo malloc/calloc/realloc se aaya, wahi free. Stack wale variables free mat karo.
- free(NULL) safe hai (kuch nahi karta) — par free ke baad pointer NULL kar do taaki dangling na rahe.
Memory leak, NULL check aur heap traps
int *p = (int *)malloc(sizeof(int));
if (p == NULL) { // HAR malloc ke baad
printf("Memory nahi mili!\n");
return 1;
}
// ... kaam karo ...
free(p);
p = NULL; // free ke baad — safe
- Memory leak: malloc kiya par free bhool gaye — block block badhta rehta hai, program chhota hota jaata hai. Long-running programs ke liye serious bug.
- Dangling: free ke baad *p use karna — garbage/crash. free ke turant baad p = NULL.
- Double free: do baar free = heap corruption (crash ya exploit). Ek baar hi.
- NULL check: heap bahar ho sakta hai (system low) — andha deref mat karo.
- Scope mismatch: function ke andar malloc, return ke baad uska address — wo block heap pe hai toh chalega (stack address hota toh dangling).
Exercise
Question: malloc/calloc ka header file kaunsa hai? (stdio.h ya stdlib.h)
Question: calloc memory allocate karke usme kya bharta hai — garbage ya zeros?
Question: Memory wapas dene wala function ka naam? (malloc / free / realloc)
Question: n integers ke liye sahi malloc call likho — (size ke roop mein):
Common mistakes
- malloc(n) ko n integers samajhna: Wo n BYTES deta hai. n integers = n * sizeof(int) — warna aadha buffer milega aur overwrite hoga.
- Free bhool jaana: Har malloc ka ek free. Program chalte rehne do toh leak — memory dheere-dheere kha jaata hai.
- free ke baad pointer chalu rakhna: p ko NULL mat kiya toh koi aur use kar sakta hai (dangling). free(p); p = NULL; — ek line ka habit.
Heap kiraye pe milne wala godown jaisa hai — jitna chahiye utna lo, khaali karo toh kiraya bacha. Na khaali kiya = kiraya barhta rehta (memory leak):
malloc = naya godown lo (kuch bhi pada ho andar)
calloc = saaf godown lo (khali)
realloc = aur jagah maango (badhao)
free = godown khaali karo
Bina free = kiraya barhta rehta = MEMORY LEAK
Size : n * sizeof(type) — varna chhota milega- GATE: malloc/calloc/realloc farak + stack vs heap — 1-2Q.
- TCS NQT: free/NULL/dangling concepts — conceptual questions.
- Interview: memory leak, double free, malloc NULL check — classic follow-ups.
- Trap: "calloc garbage deta hai" — ulta, calloc zero deta hai (malloc garbage).
Dynamic memory clear. Agla lesson — Preprocessor & Macros — compilation se pehle chalne wala text engine.