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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Dynamic Memory – Realloc | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 38 of 50

·c

Dynamic Memory – Reallocating Arrays

10 mins

Course progress76%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • `realloc(ptr, newSize)` can shrink or grow an allocation.
  • If `newSize` is 0, behavior is implementation‑defined (often equivalent to `free`).
  • Always test the return value; on failure the original block is still valid.
  • Use `size_t` for sizes to avoid signed‑unsigned mismatches.

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("
");
    free(buf);
    return 0;
}
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonBit Manipulation TechniquesContinue to lesson 39C11 & C17 Modern FeaturesBack to C Programming Fundamentals curriculum