This program demonstrates dynamic memory allocation in C by using the malloc() function to create an array dynamically on the heap. The program adds corresponding elements from two input arrays and stores the results in a dynamically allocated output array, which is then freed to prevent memory leaks.
#include <stdio.h> // For printf() function
#include <stdlib.h> // For malloc() and free() functions
#define SIZE 5 // Size of arrays
// Function declaration
int* myAddition(int* x, int* y);
int main(){
// Input arrays
int x[] = {1,2,3,4,5};
int y[] = {10,20,30,40,50};
// Output array
int* z = myAddition(x, y);
// Print table header
printf("x\ty\tz=x+y\n");
// Print array elements
for(int i=0; i<SIZE; i++){
printf("%d\t%d\t%d\n", x[i], y[i], z[i]);
}
// Free heap memory
free(z);
return 0;
}
// Function definition
int* myAddition(int* x, int* y){
// Allocate memory
int* z = malloc(sizeof(int) * 5);
for (int i=0; i<SIZE; i++){
z[i] = x[i] + y[i];
}
// Return pointer to memory location
return z;
}
Code Explanation
1. Header Files
#include <stdio.h>: Provides theprintf()function for output.#include <stdlib.h>: Providesmalloc()for dynamic memory allocation andfree()to release allocated memory.
2. Macro Definition
#define SIZE 5defines the size of the arrays, making it easy to modify the array size.
3. Main Function
- Two static input arrays,
xandy, are initialized - A pointer
zis declared to store the address of the dynamically allocated output array returned by themyAdditionfunction. - The program prints a table displaying elements of the two input arrays (
xandy) and the resulting array (z). - The
free(z)function is called to release the memory allocated on the heap.
4. Dynamic Memory Allocation
- The
myAdditionfunction allocates memory for an array of integers usingmalloc(). The size of the memory is calculated assizeof(int) * SIZE. - The function computes the sum of corresponding elements of the input arrays and stores the results in the dynamically allocated array.
- It returns a pointer to the allocated memory.
5. Output
A table is printed where each row shows an element from x, an element from y, and their sum stored in z.
x y z=x+y 1 10 11 2 20 22 3 30 33 4 40 44 5 50 55
Conclusion
This code is a practical example of dynamic memory allocation in C, illustrating how to allocate, use, and free heap memory. Dynamic memory allocation is essential in situations where the size of the data structures cannot be determined at compile time or when working with large datasets. Proper use of malloc() and free() ensures efficient memory usage and prevents memory leaks, a critical aspect of robust programming in resource-constrained environments.
