C भाषा में कभी-कभी हमें प्रोग्राम रन टाइम के दौरान memory allocate करनी पड़ती है। इसे हम Dynamic Memory Allocation कहते हैं। इसका मतलब है कि हम compile time में नहीं, बल्कि प्रोग्राम चलने के दौरान जरूरत के अनुसार memory ले सकते हैं।
int arr[10];
C में चार मुख्य functions होते हैं:
malloc()
- Memory allocate करता है।calloc()
- Memory allocate करता है और उसे zero से initialize करता है।realloc()
- पहले allocate की गई memory का size change करता है।free()
- Memory को free करता है जो पहले allocate की गई थी।malloc()
का use memory allocate करने के लिए किया जाता है। इसका syntax है:
ptr = (cast-type*) malloc(size_in_bytes);
यह function जितनी bytes आप specify करते हैं, उतनी memory allocate करता है।
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
// 5 integers के लिए memory allocate करो
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL) {
printf("Memory allocation failed");
return 1;
}
// memory में values store करो
for(int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
printf("Values stored in dynamically allocated memory:\n");
for(int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
// allocated memory को free करो
free(ptr);
return 0;
}
malloc()
5 integers के लिए memory allocate करता है।free()
से memory release की।calloc()
भी memory allocate करता है, लेकिन allocated memory को zero से initialize करता है।
ptr = (cast-type*) calloc(num_elements, size_of_each_element);
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
// calloc से memory allocate करो
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Memory allocation failed");
return 1;
}
printf("Values after calloc (initialized to zero):\n");
for(int i = 0; i < n; i++) {
printf("%d ", ptr[i]); // सभी values zero होंगी
}
free(ptr);
return 0;
}
realloc()
पहले allocate की गई memory का size बढ़ाने या घटाने के लिए इस्तेमाल होता है।
ptr = realloc(ptr, new_size_in_bytes);
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL) {
printf("Memory allocation failed");
return 1;
}
for(int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
// memory को बढ़ाओ
n = 10;
ptr = (int*) realloc(ptr, n * sizeof(int));
// नए elements में values डालो
for(int i = 5; i < n; i++) {
ptr[i] = i + 1;
}
printf("Values after realloc:\n");
for(int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
free(ptr);
return 0;
}
जो भी memory dynamically allocate की जाती है, उसे use करने के बाद free()
function से release करना जरूरी है। इससे memory leak नहीं होती।
Dynamic Memory Allocation C programming का एक बहुत ही महत्वपूर्ण concept है जो आपको flexible और efficient programs बनाने में मदद करता है। malloc()
, calloc()
, realloc()
, और free()
functions का सही उपयोग सीखना जरूरी है ताकि memory को सही तरीके से manage किया जा सके।