Dynamic Memory Allocation
Dynamic memory allocation is a feature in C that allows you to allocate memory dynamically at runtime, rather than at compile-time. This means that you can determine the amount of memory required by your program at runtime and allocate memory accordingly.
Dynamic memory allocation in C is done using four functions defined in the stdlib.h
header file:
malloc()
: Allocates a block of memory of the specified size and returns a pointer to the first byte of the block.calloc()
: Allocates a block of memory for an array of elements, initializes them to zero and returns a pointer to the first element.realloc()
: Changes the size of an existing block of memory, and returns a pointer to the first byte of the newly allocated block.free()
: Releases a block of memory previously allocated usingmalloc()
,calloc()
, orrealloc()
.
Here's an example that demonstrates how to use malloc()
to allocate memory dynamically:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
return 0;
}
The output of the above program will be:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
In this example, the program first asks the user to enter the number of elements in an array. The malloc()
function is then used to allocate memory for the ptr
pointer, which is equivalent to an array of n
elements. The memory is initialized with values from 1
to n
, and the values are displayed. Finally, the free()
function is used to release the memory previously allocated by malloc()
.
Note that it is important to use the free()
function to release memory when it is no longer needed, as failing to do so can lead to memory leaks and reduce the performance of your program.
Leave a Comment