realloc() & free() in C

The realloc() function is used to resize previously allocated memory. The free() function is used to release dynamically allocated memory back to the system.

What is realloc()?

realloc() modifies the size of an existing memory block created with malloc() or calloc().

Syntax:

ptr = realloc(ptr, new_size);

What is free()?

free() releases dynamically allocated memory, preventing memory leaks.

free(ptr);

Important Rules

5 Practical Examples

1. Increase Memory Using realloc()

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

int main(){
    int *p = malloc(2 * sizeof(int));

    p[0] = 10;
    p[1] = 20;

    p = realloc(p, 4 * sizeof(int));

    p[2] = 30;
    p[3] = 40;

    for(int i=0;i<4;i++)
        printf("%d ", p[i]);

    free(p);
    return 0;
}

2. Shrink Memory Using realloc()

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

int main(){
    int *p = malloc(5 * sizeof(int));

    for(int i=0;i<5;i++)
        p[i] = i + 1;

    p = realloc(p, 2 * sizeof(int));

    for(int i=0;i<2;i++)
        printf("%d ", p[i]);

    free(p);
    return 0;
}

3. realloc() Returning NULL

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

int main(){
    int *p = malloc(3 * sizeof(int));

    int *temp = realloc(p, 100000000000);

    if(temp == NULL){
        printf("Reallocation failed!");
    } else {
        p = temp;
    }

    free(p);
    return 0;
}

4. Free Memory After Use

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

int main(){
    char *s = malloc(20);
    sprintf(s, "Hello C");

    printf("%s", s);

    free(s);
    return 0;
}

5. realloc() for Dynamic Array Growth

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

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

    arr[0] = 5;
    arr[1] = 10;

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

    arr[2] = 15;
    arr[3] = 20;
    arr[4] = 25;

    for(int i=0;i< n;i++)
        printf("%d ", arr[i]);

    free(arr);
    return 0;
}