Dynamic memory allocation
Dynamic memory allocation refers to the process of allocating memory at runtime (when a program is executing) rather than at compile-time.
Function | Description |
malloc | Allocates a specified number of bytes of uninitialized memory. |
Syntax : int *ptr = (int *)malloc(n * sizeof(int)); | |
calloc | Allocates a specified number of elements each of a specified size, initializing them to zero. |
Syntax : int *ptr = (int *)calloc(n, sizeof(int)); | |
realloc | Resizes previously allocated memory. |
Syntax : ptr = (int *)realloc(ptr, new_size * sizeof(int)); | |
free | Deallocates memory that was previously allocated dynamically. |
Syntax : free(ptr); |
Output :
Enter total number of elements: 3
Enter number :1
Enter number :2
Enter number :3
Smallest element is 1
Output :
Enter number of elements: 3
Enter elements: 1
2
3
Sum = 6
Output :
Enter size of array: 2
Addresses of previously allocated memory: 12588000
12588004
Enter new size of array: 3
Addresses of newly allocated memory: 12588000
12588004
12588008
- Allows flexible memory usage during program execution.
- Useful for data structures whose size is not known at compile-time.
- Helps manage memory efficiently for large or varying amounts of data.
- Requires explicit management (potential for memory leaks or dangling pointers if not handled properly).
- Can lead to fragmentation of heap memory if allocations and deallocations are frequent and not properly managed.
Dynamic memory allocation provides flexibility and efficiency in managing memory for data structures whose size or lifetime cannot be determined at compile time. However, it requires careful management to avoid memory leaks, fragmentation issues, and other pitfalls associated with manual memory management. Understanding these concepts is crucial for writing robust and reliable programs that efficiently use memory resources.