Ad Space
In C programming, memory allocation refers to the process of reserving space in the computer's memory for variables or data during program execution. There are two main types:
int a[5]; // Static allocation of a 5-integer array
<stdlib.h> header file.free() to prevent memory leaks.| Function | Syntax | Purpose |
|---|---|---|
malloc() |
ptr = (type*) malloc(size_in_bytes); |
Allocates a single block of memory. |
calloc() |
ptr = (type*) calloc(n, size_of_element); |
Allocates multiple blocks and initializes them to zero. |
realloc() |
ptr = realloc(ptr, new_size); |
Changes the size of already allocated memory. |
free() |
free(ptr); |
Frees the allocated memory. |
#include <stdio.h>
#include <stdlib.h> // Required for malloc() and free()
int main() {
int *arr, n, i, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory using malloc
// We need n * size of one int
arr = (int*) malloc(n * sizeof(int));
// Check if memory allocation was successful
if (arr == NULL) {
printf("Memory not allocated!\n");
return 0; // Exit the program
}
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Read elements into the allocated memory
}
// Calculate the sum
for (i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of elements = %d\n", sum);
// Free allocated memory
free(arr);
return 0;
}
Sample Input:
Enter the number of elements: 5 Enter 5 elements: 10 20 30 40 50Output:
Sum of elements = 150Explanation:
malloc(n * sizeof(int)) allocates memory dynamically for n integers.arr stores the base address of this allocated block.for loop calculates the sum.free(arr) releases the allocated memory to prevent memory leakage.| Feature | Static Allocation | Dynamic Allocation |
|---|---|---|
| Time of Allocation | Compile-time | Run-time |
| Memory Flexibility | Fixed size | Can grow/shrink (realloc) |
| Memory Location | Stack | Heap |
| Deallocation | Automatic | Manual (using free()) |
| Functions Used | None | malloc(), calloc(), realloc(), free() |
Ad Space