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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Implementing a Stack →← Allocating Heap Memory: malloc(), calloc(), and realloc()Next lesson: Implementing a Stack →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is a dangling pointer in C?
How do you detect use after free and double free bugs in C?
Is it safe to call free on a NULL pointer?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →