Skip to content
Learn Netverks

Lesson

Step 16/36 44% through track

malloc-free

malloc and free

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches malloc and free: the syntax, patterns, and safety habits you need before advancing in C.

Pointers and dynamic allocation are the heart of C interviews—segfaults and leaks come from misunderstanding ownership.

You will apply malloc and free in contexts like: Custom allocators, linked structures, and hand-off APIs in systems libraries.

Write C in main.c with int main(), click Run on server—the dev runner compiles with cc/gcc -std=c11 and runs the binary; read stderr for compile and linker errors (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

malloc allocates raw bytes on the heap. You are responsible for calling free exactly once when done—unlike stack memory or Java GC.

Safe allocation pattern

int *arr = malloc(n * sizeof *arr);
if (arr == NULL) {
    /* handle failure */
}
/* use arr */
free(arr);
arr = NULL;

Always check for NULL. Set pointer to NULL after free to avoid double-free mistakes.

Related functions

  • calloc — zero-initialized allocation
  • realloc — resize existing block (may move memory)

Important interview questions and answers

  1. Q: Memory leak?
    A: Allocated heap memory never freed—program keeps consuming RAM.
  2. Q: Double free?
    A: Calling free twice on the same pointer—undefined behavior, often exploitable.
  3. Q: Why sizeof *ptr in malloc?
    A: Keeps element size correct if the pointer type changes.

Self-check

  1. What should you do if malloc returns NULL?
  2. How many times may you free the same pointer?

Tip: Every malloc needs a matching free on all paths—including early returns and error branches. Set pointer to NULL after free.

Interview prep

Memory leak?

Allocated heap memory never freed—the process retains RAM until exit.

Double free?

Calling free twice on the same pointer—undefined behavior, often exploitable.

Why check malloc return?

Allocation can fail under memory pressure; dereferencing NULL is undefined behavior.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • malloc fail check?
  • Double free?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump