Dynamic memory allocation in C++ refers to the allocation of memory at runtime, allowing the program to request memory dynamically as needed. The following are the key functions under header file for dynamic memory allocation:
a. malloc(): Allocates memory block of given size in bytes. It returns a pointer to
the beginning of the block or NULL if the allocation fails. Example:
int n;
cout << “Enter the number of elements: “;
cin >> n;
int *arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) {
cout << “Memory allocation failed”; return 1; } cout << “Enter ” << n << ” numbers: “; for (int i = 0; i < n; i++) { cin >> arr[i];
}
cout << “Numbers entered: “; for (int i = 0; i < n; i++) { cout << arr[i] << ” “; } free(arr); b. calloc(): Allocates an array of elements each of which has a size of size bytes. It initializes all bytes in the allocated memory to zero. Example: int n; cout << “Enter the number of elements: “; cin >> n;
int arr = (int)calloc(n, sizeof(int));
if (arr == NULL) {
cout << “Memory allocation failed”; return 1;
}
cout << “Enter ” << n << ” numbers: “;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << “Numbers entered: “;
for (int i = 0; i < n; i++) {
cout << arr[i] << ” “;
}
free(arr);
c. realloc(): Changes the size of the previously allocated memory block. If the new
size is larger, the contents of the previously allocated memory are unchanged up
to the minimum of the old and new sizes. If the new size is smaller, the content is
unchanged up to the new size. Example:
int n;
cout << “Enter the initial number of elements: “;
cin >> n;
int *arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) {
cout << “Memory allocation failed”; return 1; } cout << “Enter ” << n << ” numbers: “; for (int i = 0; i < n; i++) { cin >> arr[i];
}
cout << “Numbers entered: “; for (int i = 0; i < n; i++) { cout << arr[i] << ” “; } int new_size; cout << “\nEnter the new size: “; cin >> new_size;
arr = (int*)realloc(arr, new_size * sizeof(int));
if (arr == NULL) {
cout << “Memory allocation failed”; return 1; } cout << “Enter ” << new_size – n << ” more numbers: “; for (int i = n; i < new_size; i++) { cin >> arr[i];
}
cout << “Numbers entered: “;
for (int i = 0; i < new_size; i++) {
cout << arr[i] << ” “;
}
free(arr);
d. free(): Deallocates the memory block pointed to by ptr, which must have been
returned by a previous call to malloc(), calloc(), or realloc(). If ptr is NULL, no
operation is performed.