Dynamic Memory Allocation in C Programming with Examples
Dynamic Memory Allocation in C Programming
Dynamic Memory Allocation (DMA) allows memory to be allocated at runtime. It is useful when the size of data is not known at compile time.
Why Use Dynamic Memory?
- Efficient memory usage
- Allocate memory when needed
- Free memory after use
- Useful for large data structures
Header File Required
#include <stdlib.h>
1. malloc()
Allocates memory but does not initialize it.
Syntax:
ptr = (type*) malloc(size);
Example:
int *ptr; ptr = (int*) malloc(5 * sizeof(int));
2. calloc()
Allocates memory and initializes it to zero.
Syntax:
ptr = (type*) calloc(number, size);
Example:
int *ptr; ptr = (int*) calloc(5, sizeof(int));
3. realloc()
Resizes previously allocated memory.
Syntax:
ptr = realloc(ptr, new_size);
4. free()
Frees the allocated memory.
Syntax:
free(ptr);
Complete Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int *ptr = (int*) malloc(n * sizeof(int));
for(int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
for(int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
free(ptr);
return 0;
}
Important Points
- Always check if malloc/calloc returns NULL
- Always free unused memory
- Avoid memory leaks
Conclusion
Dynamic memory allocation is essential for advanced C programming. After this, the next topic is Structures in C programming.
Comments
Post a Comment