Dynamic Memory Reallocation

Algorithm

Step 1: Start

Step 2: Declare pointer to integer, variables i and n

Step 3: Allocate memory for 5 integers using malloc

Step 4: Check if memory allocation was successful

Step 5: Input 5 integers

Step 6: Display the 5 integers

Step 7: Reallocate memory to store 10 integers using realloc

Step 8: Input 5 more integers

Step 9: Display all 10 integers

Step 10: Free allocated memory

Step 11: End

Flowchart

graph TD; A([Start]) --> B[Declare variables and pointer]; B --> C[Allocate memory for 5 integers]; C --> D{Memory allocated?}; D -->|No| E[/Print error and exit/]; D -->|Yes| F[/Input 5 integers/]; F --> G[/Display 5 integers/]; G --> H[Reallocate memory for 10 integers]; H --> I{Memory reallocated?}; I -->|No| J[/Print error and exit/]; I -->|Yes| K[/Input 5 more integers/]; K --> L[/Display all 10 integers/]; L --> M[Free memory]; M --> N([End]); classDef start fill:#00cc44,stroke:#006622,stroke-width:2px,color:#ffffff; classDef stop fill:#ff4444,stroke:#cc0000,stroke-width:2px,color:#ffffff; classDef process fill:#4488ff,stroke:#0044cc,stroke-width:2px,color:#ffffff; classDef decision fill:#ff8844,stroke:#cc4400,stroke-width:2px,color:#ffffff; classDef input_output fill:#ffdd44,stroke:#cc9900,stroke-width:2px,color:#000000; class A,N start,stop; class B,C,H,M process; class D,I decision; class E,J,F,G,K,L input_output;

Program

/* Program for Reallocating Memory using realloc function */
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    int n, i;
    ptr = (int *)malloc(5 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    printf("Enter 5 integers:\n");
    for (i = 0; i < 5; i++) {
        scanf("%d", &ptr[i]);
    }
    printf("Entered integers: ");
    for (i = 0; i < 5; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    ptr = (int *)realloc(ptr, 10 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }
    printf("Enter 5 more integers:\n");
    for (i = 5; i < 10; i++) {
        scanf("%d", &ptr[i]);
    }
    printf("All 10 integers: ");
    for (i = 0; i < 10; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");
    free(ptr);
    return 0;
}
                

Test Case Output
Enter 5 integers:
1 2 3 4 5
Entered integers: 1 2 3 4 5
Enter 5 more integers:
6 7 8 9 10
All 10 integers: 1 2 3 4 5 6 7 8 9 10