Here are examples illustrating how to use malloc()
and realloc()
in C programming:
C Programming: An explanation of how to use malloc() and realloc() in C programming examples
Example 1: Using malloc()
to Allocate Memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, *arr;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Allocate memory for n integers
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Initialize and print the array
for (int i = 0; i < n; i++) {
arr[i] = i + 1; // Assigning values
}
printf("Array elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Free the allocated memory
free(arr);
return 0;
}
Explanation:
- For an array of n integers, malloc() dynamically allocates memory.
- Sizeof(int) is used to determine each integer's size.
- Malloc() returns NULL if memory allocation is unsuccessful.
Example 2: Using realloc()
to Resize Allocated Memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, new_n, *arr;
printf("Enter the initial number of elements: ");
scanf("%d", &n);
// Allocate memory for n integers
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Initialize the array
for (int i = 0; i < n; i++) {
arr[i] = i + 1; // Assigning values
}
printf("Enter the new size of the array: ");
scanf("%d", &new_n);
// Resize the memory block using realloc
arr = (int *)realloc(arr, new_n * sizeof(int));
if (arr == NULL) {
printf("Memory reallocation failed.\n");
return 1;
}
// Initialize new elements if the array was expanded
for (int i = n; i < new_n; i++) {
arr[i] = i + 1;
}
// Print the resized array
printf("Resized array elements: ");
for (int i = 0; i < new_n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Free the allocated memory
free(arr);
return 0;
}
Explanation:
- Memory is first allocated for n integers by malloc().
- The memory block is resized using realloc() to make room for new_n integers.
- New elements are initialized following resizing if the array size grows.
Key Points:
-
malloc()
:- used to dynamically allocate a block of memory.
- Uninitialized memory is present.
- To make sure allocation was successful, always verify if malloc() returns NULL.
-
realloc()
:- used to resize a block of memory that has already been allocated.
- The first portion of the data is kept while shrinking, and the remaining portion is truncated.
- If expanded, unless populated manually, the new memory space may contain junk values.
-
free()
:- To prevent memory leaks, always use free() to release dynamically created memory.
- To prevent memory leaks, always use free() to release dynamically created memory.
Post a Comment