Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 38 of 50 · c

Dynamic Memory – Reallocating Arrays

Duration: 10 mins

realloc changes the size of an existing allocation while preserving its content.

int *arr = malloc(5 * sizeof *arr);
/* ... fill ... */
arr = realloc(arr, 10 * sizeof *arr); // grow to 10 elements

If the block cannot be enlarged in place, realloc allocates a new block, copies the old data, frees the old block, and returns the new pointer. Always assign to a temporary variable first to avoid losing the original pointer on failure.


📚 Example: Growing an Integer Buffer

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

int main(void) {
    size_t cap = 4, used = 0;
    int *buf = malloc(cap * sizeof *buf);
    if (!buf) return 1;
    for (int i = 0; i < 12; ++i) {
        if (used == cap) {
            size_t newCap = cap * 2;
            int *tmp = realloc(buf, newCap * sizeof *tmp);
            if (!tmp) { free(buf); return 1; }
            buf = tmp; cap = newCap;
        }
        buf[used++] = i * i;
    }
    for (size_t i = 0; i < used; ++i) printf("%d ", buf[i]);
    printf("\n");
    free(buf);
    return 0;
}
Previous: Bit Manipulation TechniquesNext: C11 & C17 Modern Features