Memory Management: malloc, calloc, realloc, and free in C
C provides functions for dynamic memory allocation and deallocation. malloc is used to allocate a block of memory, calloc initializes the allocated memory to zero, realloc changes the size of an allocated block, and free deallocates the memory.
#include <stdio.h>
#include <stdlib.h>
int main() {
int* nums = (int*)malloc(5 * sizeof(int));
if (nums == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i < 5; i++) {
nums[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", nums[i]);
}
printf("\n");
// Resizing the allocated memory
int* resizedNums = (int*)realloc(nums, 10 * sizeof(int));
if (resizedNums == NULL) {
printf("Memory reallocation failed.\n");
free(nums); // Free original memory if reallocation fails
return 1;
}
for (int i = 5; i < 10; i++) {
resizedNums[i] = i + 1;
}
for (int i = 0; i < 10; i++) {
printf("%d ", resizedNums[i]);
}
printf("\n");
free(resizedNums); // Deallocate the memory
return 0;
}
This example demonstrates allocating memory for an array of integers, resizing the memory, and freeing the allocated memory.
No comments:
Post a Comment