NBC 103 • Practical #12

Dynamic Memory Allocation (malloc & free)

Aim: To allocate heap memory dynamically using malloc(), compute array statistics, and deallocate with free().

Step-by-Step Algorithm & Logic

  • 11. Declare pointer int *arr and size n = 5.
  • 22. Allocate memory: arr = (int *)malloc(n * sizeof(int)).
  • 33. Verify (arr != NULL) to ensure heap was not exhausted.
  • 44. Populate array, compute sum and average.
  • 55. Free heap memory: free(arr); arr = NULL.

Complete Tested Source Code

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

int main(void) {
    int n = 5;
    int *arr = (int *)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Error: Heap allocation failed!\n");
        return 1;
    }

    int sampleValues[] = {12, 28, 45, 67, 88};
    int sum = 0;

    for (int i = 0; i < n; i++) {
        arr[i] = sampleValues[i];
        sum += arr[i];
    }

    printf("=== Dynamic Heap Array Allocation ===\n");
    printf("Elements: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\nSum = %d | Average = %.2f\n", sum, (float)sum / n);

    free(arr);
    arr = NULL;
    printf("Heap memory released successfully.\n");
    return 0;
}

Sample Input:

Array size = 5, Values = [12, 28, 45, 67, 88]

Sample Output:

Sum = 240 | Average = 48.00
Heap memory released successfully.

Practical Exam Viva Questions (Exp #12)

1 Questions
1

What is a Memory Leak and how does free() prevent it?