C Memory Management Example

📌 C Memory Management Example (Complete Program)

Here is a full practical example demonstrating malloc, calloc, realloc, and free all in one program.


✅ Full Example: Dynamic Array with Memory Operations

#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;
}


🧠 What This Program Demonstrates

Function Purpose
malloc() Allocates memory without initializing values
realloc() Resizes previously allocated memory
free() Releases allocated memory

📌 Output Example

Enter number of elements: 5
Memory allocated using malloc.
Enter 5 elements:
10 20 30 40 50

Values stored in array:
10 20 30 40 50

Enter new size (larger than previous): 8
Memory reallocated using realloc.

Updated array values:
10 20 30 40 50 0 0 0

Memory freed successfully.


🚀 Key Best Practices

✔ Always check if memory allocation succeeded (ptr != NULL)
✔ Initialize memory when needed
✔ Always free memory when finished to prevent memory leaks
✔ Use realloc() only on dynamically allocated memory

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *