Dynamic Memory Allocation
Understanding Dynamic Memory Management in C Programming
Introduction to Dynamic Memory (डायनामिक मेमोरी का परिचय)
Dynamic memory allocation runtime पर memory को allocate करने की facility provide करता है। ये program को flexible बनाता है और memory का efficient use करता है।
Dynamic memory allocation provides the facility to allocate memory at runtime. It makes programs flexible and enables efficient memory usage.
Key Points (मुख्य बिंदु):
- Dynamic memory runtime पर allocate होती है
- Dynamic memory is allocated at runtime
- Memory heap section में allocate होती है
- Memory is allocated in heap section
- Programmer को manually memory manage करनी पड़ती है
- Programmer needs to manage memory manually
Memory Allocation Functions (मेमोरी एलोकेशन फंक्शन्स)
Dynamic memory allocation के लिए main functions:
Main functions for dynamic memory allocation:
#include
// malloc() - Memory Allocation
int *ptr = (int*)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
// calloc() - Contiguous Allocation
int *ptr = (int*)calloc(5, sizeof(int)); // Allocates and initializes to 0
// realloc() - Reallocation
ptr = (int*)realloc(ptr, 10 * sizeof(int)); // Resizes allocated memory
// free() - Memory Deallocation
free(ptr); // Frees allocated memory
Function (फंक्शन) | Description (विवरण) | Example (उदाहरण) |
---|---|---|
malloc() | Memory allocate करता है, initialized नहीं करता | malloc(10 * sizeof(int)) |
malloc() | Allocates memory, doesn't initialize | malloc(10 * sizeof(int)) |
calloc() | Memory allocate करता है और zero से initialize करता है | calloc(5, sizeof(int)) |
calloc() | Allocates and initializes to zero | calloc(5, sizeof(int)) |
Practical Examples (प्रैक्टिकल उदाहरण)
Dynamic memory allocation के practical examples:
Practical examples of dynamic memory allocation:
// Dynamic array
int n;
printf("Enter size of array: ");
scanf("%d", &n);
int *arr = (int*)malloc(n * sizeof(int));
// Dynamic string
char *str = (char*)malloc(50 * sizeof(char));
strcpy(str, "Hello World");
// Dynamic structure
struct Student {
char name[50];
int roll;
};
struct Student *s = (struct Student*)malloc(sizeof(struct Student));
// Memory reallocation
arr = (int*)realloc(arr, 2 * n * sizeof(int)); // Double the size
malloc()
calloc()
realloc()
free()
Best Practices (सर्वोत्तम प्रथाएं)
Dynamic memory के साथ काम करने के best practices:
Best practices for working with dynamic memory: