C Lesson 49 – Memory Management Project | Dataplexa

Memory Management Project in C

In this lesson, we build a small but powerful project that demonstrates how memory is allocated, resized, and released dynamically in C.

This project reflects how real applications manage memory efficiently.


Project Goal

Build a program that:

  • Dynamically allocates memory for integers
  • Accepts user input
  • Expands memory when needed
  • Safely releases memory

Step 1: Allocating Initial Memory

We begin by allocating memory using malloc.


int *arr = (int*) malloc(3 * sizeof(int));

This reserves memory for 3 integers.


Step 2: Storing User Input


for(int i = 0; i < 3; i++) {
    scanf("%d", &arr[i]);
}

User data is now stored in dynamically allocated memory.


Step 3: Expanding Memory Using realloc

Suppose the user wants to add more numbers.


arr = (int*) realloc(arr, 5 * sizeof(int));

The memory block now holds 5 integers instead of 3.


Step 4: Complete Program


#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int i;

    arr = (int*) malloc(3 * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed");
        return 1;
    }

    printf("Enter 3 numbers:\n");
    for (i = 0; i < 3; i++) {
        scanf("%d", &arr[i]);
    }

    arr = (int*) realloc(arr, 5 * sizeof(int));

    printf("Enter 2 more numbers:\n");
    for (i = 3; i < 5; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Stored numbers:\n");
    for (i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}

Why free() Is Important

Failing to release memory causes memory leaks, which can crash long-running applications.

Always release dynamically allocated memory when it is no longer needed.


Real-World Use Cases

  • Managing user input lists
  • Dynamic data buffers
  • File data processing
  • Real-time applications

Quiz

Q1: Which function allocates memory initially?

malloc()

Q2: Which function resizes allocated memory?

realloc()

Q3: What happens if memory is not freed?

Memory leak

Q4: Which header file supports memory functions?

stdlib.h

Q5: Can realloc return NULL?

Yes


Mini Practice

  • Allow user to keep adding numbers dynamically
  • Use calloc instead of malloc
  • Add error handling for failed realloc