Pointers and Memory

Dynamic Memory Management

Allocate a runtime-sized array and release it safely.

What is Dynamic Memory Management?

Dynamic storage is needed when an object's size or lifetime cannot be fixed at compile time.

Important points

  • Every pointer must refer to a live compatible object or be null.
  • Pair each owned allocation with exactly one release.
  • Prefer clear ownership and const-correct interfaces.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t count = 5;
    int *values = calloc(count, sizeof *values);
    if (!values) return 1;
    for (size_t i = 0; i < count; ++i) values[i] = (int)(i * i);
    printf("last=%d\n", values[count - 1]);
    free(values);
    return 0;
}
Get a Run button for this example Result of running the code
last=16
C++
Run code →
main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values(5);
    for (std::size_t i = 0; i < values.size(); ++i) values[i] = static_cast<int>(i * i);
    std::cout << "last=" << values.back() << '\n';
}
Get a Run button for this example Result of running the code
last=16

C and C++ comparison

C requires matching calloc or malloc with free and checking allocation failure. A C++ vector owns its memory, releases it automatically, and remains safe if an exception occurs.

C

Ownership and cleanup are conventions enforced by the programmer.

C++

Containers and RAII types can encode ownership and cleanup in object lifetimes.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Test null and allocation-failure paths.
  • Run with AddressSanitizer and UndefinedBehaviorSanitizer.
  • Document whether every pointer owns or only observes its object.

Dynamic memory in C and C++

int *a = malloc(n * sizeof *a);C: allocate an uninitialized array of n ints
int *a = calloc(n, sizeof *a);C: allocate n ints set to zero
if (a == NULL) { /* out of memory */ }Always check the result
int *bigger = realloc(a, m * sizeof *a);C: resize; keep the old pointer until realloc succeeds
free(a); a = NULL;C: release the memory, then clear the pointer
std::vector<int> v(n);C++: a resizable array that frees itself
auto p = std::make_unique<Item>();C++: one object owned by a smart pointer
new / delete, new[] / delete[]C++: manual allocation (prefer vector and smart pointers)

Common mistakes with dynamic memory

Not checking for NULL

malloc returns NULL when it cannot allocate. Writing through it crashes the program.

Problem
int *data = malloc(1000 * sizeof *data);
data[0] = 1;                /* crash if malloc failed */
Fix
int *data = malloc(1000 * sizeof *data);
if (data == NULL) return 1;
data[0] = 1;

Losing the block when realloc fails

If realloc fails it returns NULL and the old block is still allocated. Assigning straight back leaks it.

Problem
data = realloc(data, 2000 * sizeof *data);   /* old block lost on failure */
Fix
int *bigger = realloc(data, 2000 * sizeof *data);
if (bigger == NULL) { free(data); return 1; }
data = bigger;

Using memory after free

After free the pointer still holds the old address, but the memory is no longer yours.

Problem
free(data);
printf("%d\n", data[0]);   /* use after free */
Fix
free(data);
data = NULL;               /* later use fails fast instead of reading garbage */

Frequently asked questions

What is the difference between malloc and calloc?

malloc allocates memory without initializing it. calloc takes a count and an element size and sets every byte to zero, which is handy for arrays.

What is a memory leak?

Memory that was allocated but is never freed, usually because the last pointer to it was lost. Long-running programs that leak keep growing until they run out of memory.

Should I use new and delete in C++?

Rarely. std::vector, std::string and std::make_unique manage memory automatically and free it even when an exception is thrown (RAII).

What is the difference between stack and heap memory?

Local variables live on the stack and disappear when the function returns. Heap memory from malloc or new lasts until you free it, and its size can be decided at runtime.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges