C Memory Management Example
๐ C Memory Management Example Here is a full practical of C Memory Management Example demonstrating malloc, calloc, realloc, and free all in one program. โ Full Example: Dynamic Array with Memory Operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <stdio.h> #include <stdlib.h> int main() { int *arr; int n; // Step 1: Ask user for the size printf("Enter number of elements: "); scanf("%d", &n); // Step 2: Allocate memory using malloc arr = (int *)malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; } printf("\nMemory allocated using malloc.\n"); // Step 3: Take user input printf("Enter %d elements:\n", n); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } // Step 4: Display values printf("\nValues stored in array:\n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } // Step 5: Increase memory using realloc int newSize; printf("\n\nEnter new size (larger than previous): "); scanf("%d", &newSize); arr = (int *)realloc(arr, newSize * sizeof(int)); if (arr == NULL) { printf("Memory reallocation failed!\n"); return 1; } printf("\nMemory reallocated using realloc.\n"); // Step 6: Initialize new values (if size increased) for (int i = n; i < newSize; i++) { arr[i] = 0; } // Step 7: Display updated array printf("\nUpdated array values:\n"); for (int i = 0; i < newSize; i++) { printf("%d ", arr[i]); } // Step 8: Free allocated memory free(arr); printf("\n\nMemory freed successfully.\n"); return 0; } |
...
