C Memory Example

This comprehensive example demonstrates allocating, accessing, resizing, and deallocating memory in a single program.

Example: Comprehensive Memory Management

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

int main() {
    int *arr;
    int n = 3;

    arr = (int *)malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

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

    arr = (int *)realloc(arr, 5 * sizeof(int));
    if (arr == NULL) {
        printf("Reallocation failed!\n");
        return 1;
    }

    arr[3] = 4;
    arr[4] = 5;

    for (int i = 0; i < 5; i++) {
        printf("Value at index %d: %d\n", i, arr[i]);
    }

    free(arr);
    return 0;
}

Code Explanation: This program demonstrates all aspects of memory management: allocation with malloc(), resizing with realloc(), accessing with pointers, and deallocating with free().