Dynamic Memory Allocation in C in Hindi: malloc(), calloc(), realloc() और free() सीखें

Dynamic Memory Allocation in C programming एक ऐसी technique है जिसमें program run होते समय, यानी runtime पर, memory allocate की जाती है। जब array या data का exact size पहले से पता नहीं होता, तब dynamic memory allocation बहुत useful होता है। 

इस article में आप C में dynamic memory allocation को आसान Hindi में समझेंगे—malloc(), calloc(), realloc() और free() functions, syntax, examples, memory leak, dangling pointer और best practices के साथ।

Dynamic Memory Allocation क्या है?

Dynamic Memory Allocation का मतलब है कि program को execution के दौरान अपनी ज़रूरत के अनुसार memory मिलती है। यह memory आमतौर पर Heap Memory से allocate होती है और उसे access करने के लिए pointer का use किया जाता है।

मान लीजिए आपको user से 10 students के marks store करने हैं। अगर user बाद में कहे कि उसे 50 students के marks store करने हैं, तो fixed array में problem हो सकती है। Dynamic memory allocation में आप user के input के हिसाब से memory allocate कर सकते हैं।

Example : 

int *arr;
int n;

scanf("%d", &n);

arr = (int *)malloc(n * sizeof(int));

यहाँ n की value runtime पर user से ली जाती है, इसलिए memory भी runtime पर allocate होती है।

Static और Dynamic Memory Allocation में अंतर

C में memory allocation मुख्य रूप से दो तरीकों से होती है: static या automatic allocation, और dynamic allocation. Static allocation में size compile time पर fixed होता है, जबकि dynamic allocation में size runtime पर decide होता है।

निचे दिये गये Table से समझें:

FeatureStatic AllocationDynamic Allocation
Memory कब मिलती हैCompile time परRuntime पर
SizeFixed होता हैUser input या logic के अनुसार
Memory AreaStackHeap
Resize संभव है?नहीं`realloc()` से हाँ
Memory ReleaseAutomatic`free()` से manually
Example`int arr[10];``int *arr = malloc(10 * sizeof(int));`

Static array में अगर आपने 10 elements के लिए memory ली, तो आप उसमें 11वाँ element store नहीं कर सकते। लेकिन dynamic memory में ज़रूरत पड़ने पर realloc() से memory बढ़ाई जा सकती है।

Dynamic Memory Allocation क्यों ज़रूरी है?

Dynamic memory allocation कई situations में काम आता है, खासकर जब data की मात्रा पहले से fixed न हो।

  • User से array का size input लेना हो
  • File से unknown number of records read करने हों
  • Linked List, Tree, Graph जैसे data structures बनाने हों
  • Memory को ज़रूरत के अनुसार बढ़ाना या घटाना हो
  • Memory waste कम करना हो
  • Large data को efficiently handle करना हो

उदाहरण के लिए, अगर आप एक student management program बना रहे हैं, तो students की संख्या हर बार अलग हो सकती है। ऐसे में dynamic array बेहतर option है।

Dynamic Memory Allocation के लिए Header File

C में dynamic memory allocation के लिए stdlib.h header file use होती है। इसमें malloc(), calloc(), realloc() और free() functions declare होते हैं।

#include <stdlib.h>

इस header file के बिना dynamic memory functions use करने पर compiler error आ सकता है।

malloc() Function in C

malloc() का full form Memory Allocation है। यह function requested size के बराबर bytes का एक memory block allocate करता है और उस memory block के starting address का pointer return करता है।

malloc() allocated memory को initialize नहीं करता। इसलिए newly allocated memory में garbage values हो सकती हैं।

malloc() का Syntax

ptr = (data_type *)malloc(size_in_bytes);

Syntax Part by part explanation

  • ptr – एक pointer variable है, जिसमे memory block का starting address store होता है।
  • = – assignment operator है; malloc() से मिलने वाला address ptr में save होता है।
  • (data_type *) – type cast है। malloc() void * return करता है,इसलिये इससे data_type * में convert किया जाता है, जैसे int *, float *, या char *.
  • malloc — “memory allocation” का function है, जो <stdlib.h> header में होता है। ये heap से requested bytes का contiguous memory block reserve करता है।
  • size_in_bytes — कितने bytes की memory चाहिये, ये बताता है। Usually sizeof(data_type) uses होता है, जैसे sizeof(int).

malloc() Example Program – Allocate Dynamic Memory

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    int *arr;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    arr = (int *)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    printf("Array elements: ");

    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    arr = NULL;

    return 0;
}
▶️ Output Result
Enter number of elements: 5 Array elements: 1 2 3 4 5

malloc() के Important Points

  • malloc() requested bytes का contiguous memory block allocate करता है।
  • Success होने पर यह memory block का pointer return करता है।
  • Memory available न होने पर NULL return करता है।
  • Allocated memory uninitialized रहती है।
  • sizeof() का use करके correct memory size calculate करें।
Memory allocation using malloc() in C with an array of five integers.

calloc() Function in C

calloc() का full form Contiguous Allocation है। यह function multiple elements के लिए memory allocate करता है और सभी allocated bytes को 0 से initialize कर देता है।

calloc() का Syntax

ptr = (data_type *)calloc(number_of_elements, size_of_each_element);

Syntax Part by part explanation

  • ptr — यह एक pointer variable है, जिसमें calloc() से मिली memory block का starting address store होता है। सफल allocation पर यह allocated memory के पहले byte का address return करता है।
  • = — यह assignment operator है। इसका मतलब है कि calloc() से मिलने वाला address ptr variable में save हो जाएगा। 
  • (data_type *) — यह type cast है। calloc() void * return करता है, इसलिए इसे required pointer type में convert किया जाता है, जैसे int *, float *, या char *.
  • calloc — यह contiguous allocation का function है, जो <stdlib.h> header में होता है। यह heap से requested memory allocate करता है और उसे 0 से initialize करता है।
  • number_of_elements — यह बताता है कि कितने elements के लिए memory चाहिए। जैसे 5 integers के लिए 5 लिखा जाएगा।
  • size_of_each_element — यह बताता है कि हर एक element कितने bytes का है। इसके लिए आमतौर पर sizeof(data_type) use होता है, जैसे sizeof(int).

calloc() Example Program – Allocate Dynamic Memory for 5 integers

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 5;
    int *arr;

    arr = (int *)calloc(n, sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!");
        return 1;
    }

    printf("Array elements: ");

    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    arr = NULL;

    return 0;
}
▶️ Output Result
Array elements: 0 0 0 0 0
Pointmalloc()calloc()
Full FormMemory AllocationContiguous Allocation
ParametersTotal bytesNumber of elements और element size
Initializationनहीं करतासभी bytes को 0 करता है
Garbage Valuesहो सकती हैंनहीं होतीं
Best UseGeneral memory allocationArray या structured data

अगर आपको शुरू से ही array की सभी values 0 चाहिए, तो calloc() ज़्यादा suitable है।

Memory allocation using calloc() in C with five zero-initialized integer elements

realloc() Function in C

realloc() का full form Re-Allocation है। यह function पहले से allocated memory block का size बदलने के लिए use होता है। इससे memory को increase या decrease किया जा सकता है।

realloc() का Syntax

ptr = (data_type *)realloc(ptr, new_size);

realloc() Syntax Part by part explanation

  • ptr — यह एक pointer variable है, जिसमें पहले malloc(), calloc(), या realloc() से मिली memory का starting address store होता है। realloc() इसी memory block का size बदलता है।
  • = — यह assignment operator है। realloc() से मिलने वाला नया address वापस ptr में save होता है, क्योंकि memory block की location बदल सकती है।
  • (data_type *) — यह type cast है। realloc() void * return करता है, इसलिए इसे required pointer type में convert किया जाता है, जैसे int *, float *, या char *.
  • realloc — यह reallocation function है, जो <stdlib.h> header में होता है। यह पहले से allocated memory block का size change करता है।
  • पहला ptr — यह बताता है कि किस memory block का size बदलना है। यह pointer पहले malloc(), calloc(), या realloc() से मिला होना चाहिए और free() से release नहीं हुआ होना चाहिए।
  • new_size — यह बताता है कि memory block का नया size कितने bytes का होगा। आमतौर पर इसे number_of_elements * sizeof(data_type) के रूप में लिखा जाता है।

realloc() Example Program

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int n = 3;

    arr = (int *)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    n = 5;

    int *temp = (int *)realloc(arr, n * sizeof(int));

    if (temp == NULL) {
        printf("Memory reallocation failed!");
        free(arr);
        return 1;
    }

    arr = temp;

    arr[3] = 4;
    arr[4] = 5;

    printf("Updated array: ");

    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    arr = NULL;

    return 0;
}
▶️ Output Result
Updated array: 1 2 3 4 5

realloc() के Important Points

  • realloc() पुरानी memory का size change करता है।
  • पुराने data तब तक safe रहते हैं जब तक memory block का size बढ़ाया या घटाया जा रहा हो।
  • नई memory uninitialized हो सकती है।
  • realloc() fail होने पर NULL return कर सकता है।
  • Directly arr = realloc(arr, new_size); लिखना risky हो सकता है, क्योंकि fail होने पर original pointer खो सकता है।

इसलिए best practice है कि realloc() का result पहले temporary pointer में store करें।

int *temp = realloc(arr, new_size);

if (temp == NULL) {
	printf("Reallocation failed");
} else {
	arr = temp;
}
Memory resizing using realloc() in C showing an array expanding from five to ten integers

free() Function in C

free() function dynamically allocated memory को release करने के लिए use होता है। जब malloc(), calloc() या realloc() से ली गई memory की ज़रूरत खत्म हो जाए, तो उसे free() से release करना चाहिए।

free() का Syntax

free(ptr);

ptr = NULL;

free() Example Program

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;

    ptr = (int *)malloc(sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed!");
        return 1;
    }

    *ptr = 50;

    printf("Value = %d\n", *ptr);

    free(ptr);
    ptr = NULL;

    return 0;
}
▶️ Output Result
Value = 50

free() क्यों ज़रूरी है?

free() का use न करने पर allocated memory program में बनी रह सकती है। इससे memory leak हो सकता है।

free() के बाद pointer को NULL करना अच्छी practice है, क्योंकि इससे accidental use या dangling pointer की problem कम होती है।

free(ptr);

ptr = NULL;

Dynamic Array in C — Complete Example Program

नीचे दिया गया program user से students की संख्या और उनके marks लेता है। फिर वह total marks calculate करता है।

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n, sum = 0;
    int *marks;

    printf("Enter number of students: ");
    scanf("%d", &n);

    marks = (int *)malloc(n * sizeof(int));

    if (marks == NULL) {
        printf("Memory allocation failed!");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        printf("Enter marks of student %d: ", i + 1);
        scanf("%d", &marks[i]);
    }

    for (int i = 0; i < n; i++) {
        sum += marks[i];
    }

    printf("\nTotal marks = %d\n", sum);

    free(marks);
    marks = NULL;

    return 0;
}
▶️ Output Result
Enter number of students: 3 Enter marks of student 1: 80 Enter marks of student 2: 90 Enter marks of student 3: 70Total marks = 240

यह example dynamic memory allocation का practical use दिखाता है। यहाँ array का size user input के आधार पर decide होता है।

Memory Leak क्या है?

जब dynamically allocated memory को free() न किया जाए, तो वह memory आगे के लिए available नहीं हो पाती। इसे Memory Leak कहते हैं।

int *ptr = malloc(100);

// free(ptr); नहीं किया गया 

ऊपर दिए code में memory allocate हुई, लेकिन उसे release नहीं किया गया। इससे memory leak हो सकता है।

Memory Leak से बचने के लिए

  • हर malloc(), calloc() या realloc() के बाद free() use करें। 
  • Pointer variable को overwrite करने से पहले पुरानी memory free करें।
  • realloc() के समय temporary pointer use करें।
  • Program exit होने से पहले सभी dynamic memory release करें।

Dangling Pointer क्या है?

जब किसी pointer को free() कर दिया जाए, लेकिन उसके बाद भी उस pointer को use किया जाए, तो वह Dangling Pointer बन जाता है। इससे undefined behavior, crash या wrong output आ सकता है।

int *ptr = malloc(sizeof(int));

free(ptr);

// Wrong Practice
*ptr = 10;

free() के बाद ptr अब valid memory को point नहीं करता। इसलिए उसे दोबारा use नहीं करना चाहिए।

Correct Way

int *ptr = malloc(sizeof(int));

free(ptr);
ptr = NULL;

Common Mistakes in Dynamic Memory Allocation

Beginners अक्सर इन mistakes को करते हैं:

  • malloc() या calloc() का NULL check न करना
  • free() call न करना
  • एक ही pointer को दो बार free() करना
  • free() के बाद pointer को use करना
  • NULL pointer को dereference करना
  • sizeof() के बजाय hard coded memory size लिखना
  • realloc() का result directly original pointer में assign करना
  • Memory leak create करना

free() को केवल उसी pointer के साथ use करें जो पहले malloc(), calloc() या realloc() से return हुआ हो। अन्यथा undefined behavior हो सकता है।

FunctionPurposeInitializationSyntax
malloc()Runtime पर memory allocate करनानहीं`malloc(size)`
calloc()Multiple elements के लिए memory allocate करना0`calloc(n, size)`
realloc()पुरानी memory का size बदलनापुराना data preserve`realloc(ptr, new_size)`
free()Allocated memory release करना—`free(ptr)`

C में dynamic memory management के लिए यही चार main functions use होते हैं: malloc(), calloc(), realloc() और free().

Best Practices for Beginners

  • हमेशा malloc(), calloc() और realloc() का NULL check करें।
  • Memory size calculate करने के लिए sizeof() use करें।
  • Memory use होने के बाद free() ज़रूर call करें।
  • free() के बाद pointer को NULL set करें।
  • realloc() के लिए temporary pointer use करें।
  • Dynamic memory को pointer के through access करें।
  • Memory leak और dangling pointer से बचें।

Conclusion ( निष्कर्ष )

इस post में Dynamic Memory Allocation in C को detail में पढ़े, जिसमे आपने चारों  function (malloc(), calloc(), realloc() और free()) को depth में समझें Example program के साथ।  Dynamic Memory Allocation C programming का एक important concept है जो program को flexible और memory-efficient बनाता है। malloc() से memory allocate करें, calloc() से zero-initialized memory लें, realloc() से memory size change करें, और free() से memory release करें।

Beginners के लिए सबसे ज़रूरी rule है: जितनी memory allocate की है, उतनी ही responsibility लेकर उसे free() करें। इससे आपका C program stable, efficient और memory-safe बनेगा। अगर आपको यह post useful लगा हो और आप इससे कुछ सीखें हो तो अपने दोस्तों के साथ शेयर करें जो C Programming सीख रहें हों। 

FAQs

Q 1: Dynamic Memory Allocation in C क्या है?
Ans: Dynamic Memory Allocation C में runtime पर memory allocate करने की process है। इसके लिए malloc(), calloc(), realloc() और free() functions use होते हैं।
Q 2: malloc() और calloc() में क्या अंतर है?
Ans: malloc() memory allocate करता है लेकिन initialize नहीं करता, जबकि calloc() memory allocate करके उसे 0 से initialize करता है।
Q 3: free() क्यों ज़रूरी है?
Ans: free() dynamically allocated memory को release करता है। इससे memory leak से बचा जा सकता है।
Q 4: realloc() कब use करते हैं?
Ans: जब पहले से allocated memory का size बढ़ाना या घटाना हो, तब realloc() use किया जाता है।
Q 5: Dynamic Memory कहाँ allocation होती है?
Ans: Dynamic memory आमतौर पर Heap Memory में allocate होती है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top