💻 Unit 2 – Part C

C Programming

⬅ Back to Unit 2

Ad Space

Part C: Additional Questions

1. Explain in detail the different types of memory allocations in C. Write a program to dynamically allocate memory for an array and calculate the sum of the elements in it.

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:

1. Static Memory Allocation

Example:
int a[5]; // Static allocation of a 5-integer array

2. Dynamic Memory Allocation

Dynamic Memory Allocation Functions:
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.

Program: Dynamic Memory Allocation for an Array and Calculate Sum

#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 50
Output:
Sum of elements = 150
Explanation:

Difference Between Static and Dynamic Memory Allocation

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