Releasing Memory and Avoiding Leaks | Programming in C

UPI Study › Courses › Programming in C › Free lessons › Lesson 11.3 Free with a free account

Releasing Memory and Avoiding Leaks

Programming in C · Chapter 11: Dynamic Memory, Linked Lists, Stacks, and QueuesSection 11.3 · lesson 73 of 787 min · free with a free account

← Allocating Heap Memory: malloc(), calloc(), and realloc()Next lesson: Implementing a Stack →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Using free correctly and catching leaks, dangling pointers, and double frees.

  • Explain what free accepts and why the pointer should be set to NULL afterward
  • Identify memory leaks and find them with tools such as leaks or Valgrind
  • Recognize use-after-free and double-free bugs and catch them with AddressSanitizer
  • Write cleanup helpers that free memory and clear the caller's pointer

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,103 words). Read along, or search it.

Opening Question

A Kiosk That Slowed Down All Weekend

Imagine borrowing a game controller from the arcade desk, and walking out with it. Tonight, nobody notices. After a hundred players do the same, the desk is empty, and the arcade is stuck. A C program that borrows heap memory and never gives it back behaves the same way. Sam left the score kiosk running over a weekend. It printed no errors, but it got slower every hour. Why? To find out, you'll learn free, memory leaks, dangling pointers, and a safe way to clean up.

Core Rule

Free the Block, Then Clear the Pointer

free, from stdlib dot h, hands a heap block back, so it can be used again. You may pass it only an address that came from malloc, calloc or realloc, exactly as you got it. Or NULL. After free of tokens, the block isn't yours any more. But the pointer variable still holds the old address. So the next line sets tokens to NULL, which means it points at nothing. Now the test, tokens equals NULL, tells the truth. And the second free is harmless, because freeing NULL does nothing, by rule. Build and run. Tokens: 25. tokens is NULL, safe. Still running.

Memory Leak

Losing the Only Copy of an Address

Now the first way it goes wrong. A memory leak is a block that's still allocated, but that nothing in the program can reach any more. Here, box gets block A, which holds 10. Then box is pointed at a new block, B. That overwrote the only copy of A's address. Nobody knows where A is any more, so nobody can ever free it. Build and run. Block A holds 10. Block B holds 20. The output looks perfectly normal. And that's the danger. A leak never prints an error. A program that leaks inside a loop just keeps growing.

Finding Leaks

Leak Checkers on macOS and Linux

To see a leak, you need a tool. macOS comes with one, called leaks. It runs a program, and checks the heap as the program exits. Here's its report for this program, from a run on this Mac: one leak, sixteen bytes in all. The int needed only four bytes, but this Mac's malloc hands out at least sixteen at a time. On Linux, tools such as Valgrind do the same job. Real teams run checks like these all the time. The fix is one line: free box before you point it at a new block. Then the same check reports zero leaks.

Dangling Pointers

Use After Free and Double Free

The opposite problem is a dangling pointer: a pointer that still holds the address of a block that was already freed. free doesn't change the pointer. It still looks fine. But the block belongs to the heap again, and may be handed to someone else. Two bugs follow from it. Use after free means reading or writing through the pointer after the free. Double free means freeing the same block twice. It can corrupt the heap's records, and crash later, somewhere unrelated. Both are undefined behavior, as in 7.1. A crash on one run can become silent wrong data on the next.

Sanitizer Demo

AddressSanitizer Catches a Bad Read

Here's a use after free. Build it with warnings on, and clang says nothing at all. Don't run the plain program and trust what it prints. Whatever it shows means nothing. Instead, rebuild it with AddressSanitizer: dash f sanitize equals address, plus dash g for line numbers. Now the run stops with a report: heap use after free, a read of four bytes. Further down, the report names the lines: the bad read on line 8, and the free on line 7. It points straight at the bug.

Sanitizer Demo

Catching a Double Free

And here's a double free. Again, a plain build gives no warning. Under AddressSanitizer, the run stops: attempting double free. Its report names line 6, and the first free on line 5. The cure for both bugs is one habit: right after free, set the pointer to NULL. Then a second free of that pointer is legal, and does nothing. Rebuild and run: no report at all. So that one habit prevents both bugs.

Quick Check

NULL Never Fixes the Copies

Quick check. b is a copy of a. Then a is freed and set to NULL. After that, the program frees a again, and then frees b. Which free goes wrong? Pause and predict. Build with AddressSanitizer and run: attempting double free. So one of the two calls freed a block twice. It isn't free of a, on line 11. a is NULL there, and freeing NULL does nothing. So it's free of b, on line 12. The report's stack says so too. Setting a to NULL cleared only a. b still holds the old address, so b dangles. NULL never fixes the copies. So keep one clear owner for each block, and let only the owner free it.

Helper Function

A Release Helper With a Double Pointer

Because free-then-NULL is easy to forget, wrap it in a helper. release takes the address of the pointer: an int star star. Inside, free of star p frees the block, and star p equals NULL clears the caller's own variable. It's the same trick as passing an address to change an int, from 6.5. main releases scores twice. The second call frees NULL, which is harmless. Build and run. First score plus bonus: 105. scores is NULL.

Lists

Freeing a List and Clearing the Head

The same idea works for a list. free_all frees every node, saving next first, and then returns NULL. So the caller writes line equals free_all of line, which clears the head in the same breath. Build and run. Freed 3 nodes. The second call finds an empty list: Freed 0 nodes.

Quick Check

One Leaked Record per Game

Quick check. Back to Sam's kiosk. Each finished game saves its score in a record on the heap, and prints it. Look at the loop. When this program ends, how many of those records have leaked? Pause and predict. Three. The run itself looks fine. But the leaks tool, run on this Mac, reports three leaks, forty-eight bytes: one sixteen-byte block for every game. rec is a fresh local in every pass. When the pass ends, the only copy of that block's address is gone. That was Sam's kiosk. It ran all weekend, and every game left one record behind, so it got slower every hour. Priya's fix was one line: free rec once the score is printed. With it, the leaks report shows zero leaks. As she put it, the bug was a missing line, not a missing feature.

Key Takeaways

One Owner for Every Block

To sum up. free hands a block back. Set the pointer to NULL right after. A leak is a block nothing can reach. It never prints an error, so check with a tool. A dangling pointer leads to use after free and double free. Both are undefined behavior. Wrap cleanup in a helper, and keep one owner for each block.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Releasing Memory and Avoiding Leaks

What is a memory leak in C?
A memory leak is a heap block that is still allocated but that no pointer in the program can reach anymore, so it can never be freed. It often happens when the only pointer to a block is pointed at a new block. A leak prints no error, and a program that leaks inside a loop just keeps growing. Tools such as leaks on macOS or Valgrind on Linux report them.
What is a dangling pointer in C?
A dangling pointer still holds the address of a block that has already been freed. free does not change the pointer, so it looks valid, but the memory belongs to the heap again. Reading or writing through it is a use after free, and freeing it again is a double free; both are undefined behavior. Setting the pointer to NULL right after free prevents both through that pointer.
How do you detect use after free and double free bugs in C?
Build with AddressSanitizer by adding -fsanitize=address, plus -g for line numbers, then run the program. When the bug happens, the run stops with a report such as heap-use-after-free or attempting double free, naming the line of the bad access and the line of the earlier free. A plain build often gives no warning, and its output cannot be trusted.
Is it safe to call free on a NULL pointer?
Yes, free(NULL) does nothing, by the C standard. That is why setting a pointer to NULL after freeing it makes a second free of that pointer harmless. It does not protect copies, though: if b = a and then a is freed and set to NULL, b still holds the old address, and free(b) is a double free. Keep one clear owner for each block.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →