🏭
Memory Management

malloc() & calloc()

Runtime Par Memory Maango
💡 malloc() ek khaali warehouse space book karne jaisa hai (jo cheez andar hai wo purani/random hai), calloc() ek saaf-suthra, already-cleaned warehouse space book karne jaisa hai (sab kuch 0 se shuru).

malloc(size) heap se "size" bytes maangta hai aur us memory ka pointer return karta hai (ya NULL agar memory available na ho). Ye memory ka content garbage (random) hota hai — initialize karna khud padta hai.

calloc(count, size) bhi memory allocate karta hai, lekin do farq hain: pehla, parameters "count × size" hote hain (jaise 10 ints ke liye calloc(10, sizeof(int))); doosra, calloc automatically saari memory ko 0 se fill kar deta hai — jo malloc nahi karta.

Dono se mili memory heap par hoti hai, isliye function khatam hone ke baad bhi zinda rehti hai (stack variables ke ulat) — yehi wajah hai ki dynamic memory se function se pointer safely return kiya ja sakta hai.

int *arr1 = malloc(5 * sizeof(int));  // 5 ints, garbage values
int *arr2 = calloc(5, sizeof(int));   // 5 ints, sab 0

if (arr1 == NULL) {
  printf("Memory allocation fail hui!\n");
  return 1;
}

for (int i = 0; i < 5; i++) {
  printf("%d ", arr2[i]); // 0 0 0 0 0
}

free(arr1);
free(arr2);
🏭
malloc() ek khaali warehouse space book karne jaisa hai (jo cheez andar hai wo purani/random hai), calloc() ek saaf-suthra, already-cleaned warehouse space book karne jaisa hai (sab kuch 0 se shuru).
1 / 2
⚡ झट से Recap
  • malloc(size) = garbage memory, size bytes
  • calloc(count, size) = zero-initialized memory
  • Dono ka return NULL check karna zaroori hai
इस page में (2 subtopics)

malloc() void* return karta hai (generic pointer, koi bhi type ho sakta hai). C mein isse explicitly cast karna (jaise (int*)malloc(...)) zaroori nahi hai — C automatically void* ko kisi bhi pointer type mein convert kar deta hai. Lekin C++ mein cast zaroori hai.

Kuch developers phir bhi cast likhte hain readability ke liye, lekin modern C style guides (jaise K&R) usually cast na lagane ki salah dete hain — agar tum <stdlib.h> include karna bhool jaao, cast wali galti chhupa sakta hai jo compiler warning se pakdi jaati.

// C mein dono chalte hain, lekin cast na lagana zyada recommended hai:
int *p1 = malloc(10 * sizeof(int));         // preferred C style
int *p2 = (int*)malloc(10 * sizeof(int));   // bhi valid, lekin unnecessary
💡Tip: sizeof(*p) likhna sizeof(int) se zyada safe hai — agar kabhi p ka type badal jaaye, sizeof(*p) automatically sahi size dega bina code change kiye. Jaise: int *p = malloc(10 * sizeof(*p));

malloc()/calloc() sirf primitive types ke liye nahi, kisi bhi struct type ke liye bhi kaam karta hai — bahut common pattern hai jab runtime par pata chale ki kitne "records" (jaise students, employees) store karne hain.

typedef struct {
  char name[50];
  int age;
} Student;

int n = 3;
Student *students = malloc(n * sizeof(Student));

students[0].age = 20;
strcpy(students[0].name, "Aarav");

free(students);