Oct 28, 2024
Dynamic memory allocation in C allows changing the size of data structures, like arrays, during runtime. This flexibility is crucial for efficient memory management.
C provides four key functions for dynamic memory allocation:
malloc()calloc()free()realloc()These functions are included in the <stdlib.h> library.
malloc()void* pointer to the allocated space or NULL if allocation fails.ptr = (cast-type*) malloc(byte-size);
int* ptr = (int*) malloc(100 * sizeof(int)); // Allocates 400 bytes for 100 integers
calloc()void* pointer to the allocated space or NULL if allocation fails.ptr = (cast-type*) calloc(n, element-size);
float* ptr = (float*) calloc(25, sizeof(float)); // Allocates memory for 25 floats
free()malloc() or calloc().free(ptr);
realloc()NULL if reallocation fails.ptr = realloc(ptr, newSize);
malloc() Example#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
} else {
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]);
}
}
return 0;
}
calloc() Example#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n = 5, i;
ptr = (int*) calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
} else {
printf("Memory successfully allocated using calloc.\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]);
}
}
return 0;
}
free() Example#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = (int*) malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
free(ptr);
printf("Memory successfully freed.\n");
return 0;
}
realloc() Example#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n = 5, i;
ptr = (int*) calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
n = 10;
ptr = (int*) realloc(ptr, n * sizeof(int));
if (ptr == NULL) {
printf("Reallocation Failed\n");
exit(0);
}
for (i = 5; 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;
}
This guide covers the basics and examples of using dynamic memory allocation functions in C, demonstrating their application and syntax.*