Memory Allocation and Garbage Collection, Explained

UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 4.11 Free with a free account

Memory Allocation and Garbage Collection

Introduction to Operating Systems · Chapter 4: Memory ManagementSection 4.11 · lesson 35 of 839 min · free with a free account

← Cache CoherenceNext lesson: Peripheral Devices →

A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →

Earn 3 college credits for Introduction to Operating SystemsRecommended for credit by NCCRS · Computer Science 354 · self-paced · one payment, lifetime access

In this lesson

Fit rules, fragmentation, the C heap and garbage collection methods.

  • Apply first fit, best fit and worst fit to a list of free holes
  • Distinguish external fragmentation from internal fragmentation and explain compaction
  • Use malloc, realloc and free safely in C
  • Compare reference counting with mark-and-sweep garbage collection

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,299 words). Read along, or search it.

Opening Scene

Where Should the Flour Sack Go

Sam, who runs a small online bakery, has a storeroom shelf with a few gaps between the boxes. A new sack of flour arrives. Should it go in the first gap that's big enough, the snuggest gap, or the biggest one? Whichever Sam picks, small awkward gaps pile up. One day there's plenty of space in total, but nowhere to put the sack. Memory has the same story. And when programs finish, someone also has to clear the shelf.

Fit Rules

First Fit, Best Fit, Worst Fit

In contiguous allocation, each program gets one unbroken block of memory. As programs come and go, free memory breaks into separate holes. When a request arrives, the OS must pick a hole that's big enough. There are three common rules. First fit takes the first hole that's big enough. It's quick to find. Best fit takes the smallest hole that's big enough, leaving the smallest scrap. But it must look through every hole. Worst fit takes the largest hole, hoping the leftover is still big enough to be useful.

Code Walkthrough

Three Rules on Five Holes

This Python program tries all three rules on one list of free holes, in kilobytes: one hundred, five hundred, two hundred, three hundred, and six hundred. Four requests arrive in order: two hundred twelve, four hundred seventeen, one hundred twelve, and four hundred twenty-six. For each request, it lists the holes that fit. First fit takes the first of them, best fit the smallest, and worst fit the largest. The chosen hole then shrinks by the size of the request.

Program Output

Plenty Free, Yet a Request Fails

Run it. Holes are numbered from zero. First fit puts two hundred twelve in hole one, the five hundred. The last request, four hundred twenty-six, finds no hole at all. Best fit places all four. Worst fit fails on four hundred twenty-six too. Yet when they fail, nine hundred fifty-nine kilobytes are free in total. The largest hole is only three hundred. No rule wins every time. Real systems pick by speed, and by how the workload behaves.

Quick Check

Best Fit for a 160 KB Request

Quick check, with new holes: three hundred, one hundred fifty, seven hundred, and one hundred eighty kilobytes. One request arrives, for one hundred sixty. Which hole does best fit pick? Pause, and decide. Hole three, the one hundred eighty. It's the smallest hole that still fits, and it leaves a scrap of just twenty. Hole zero, the three hundred, is first fit's choice: the first hole big enough. And hole two, the seven hundred, is what worst fit takes.

Fragmentation

External Versus Internal Waste

That failed request is classic external fragmentation: enough free memory in total, but split into holes too small to use. There's a second kind. Internal fragmentation is waste inside a block that was handed out, because the block is bigger than the request. Say memory is handed out in fixed blocks of one hundred kilobytes. Two hundred twelve takes three blocks, and wastes eighty-eight inside. A simple test: if the waste sits between blocks, it's external. If it sits inside a block, it's internal.

Compaction

Sliding Programs to Merge Holes

The cure for external fragmentation is compaction: slide every program to one end of memory, so the holes merge into one big hole. It works, but moving programs takes time. And their addresses must be able to change. Systems with base registers, as in lesson four point six, can do it. Systems that fix addresses at compile time can't. Paging, from lesson four point eight, avoids most of this trouble, because a program no longer needs one unbroken block.

C Heap

Asking the Heap for Blocks in C

Programs also ask for memory while they run. In C, malloc asks the heap, a pool of memory for blocks of any size and lifetime, for a block. It returns a pointer to the block, or NULL if it can't. So the program checks for NULL. realloc resizes a block. Here it grows room for ten ints into room for twenty. The old pointer must not be used after that. free gives the block back. Behind these calls, the allocator keeps its own list of holes, and uses fit rules like the ones you just saw.

Program Output

A Block That Really Grew

Build it, and run it. The sums are two hundred eighty-five and two thousand four hundred seventy: the first ten squares, and then the first twenty. So the block really grew. The program prints results, not raw addresses, because addresses change from run to run. After free, it sets the pointer to NULL, so an accidental later use fails loudly, instead of quietly reading freed memory.

Three Rules

Leaks, Double Frees and Use After Free

Three rules to remember. Check for NULL. Call free exactly once for each block. And never touch a block after freeing it. Forget to free, and the program has a memory leak: it holds memory it will never use again. Free a block twice, or use it after freeing, and the program has a bug that can crash or corrupt data. The results are unpredictable, so they're not run here. One more thing: this heap is just a loose pool of memory. It's not the heap data structure from sorting.

Garbage Collection

Reference Counting Versus Mark and Sweep

Many languages, such as Java and Python, free memory for you. A garbage collector finds objects that no part of the program can reach any more, and gives their memory back. Reference counting: every object counts how many things point to it. When the count reaches zero, it's freed at once. Its flaw is a cycle. Two objects that point to each other keep each other's count at one forever, even when the program can't reach either. Tracing, most famously mark and sweep, starts from the roots: the variables the program holds directly. It marks everything it can reach, then sweeps away the rest. Cycles are no problem for it, because nothing in an unreachable cycle gets marked.

Code Walkthrough

A Toy Heap With a Cycle

This program builds a toy heap. A points to B, C and D point at each other, and E stands alone. The program holds A and E directly. Run it. Reference counting frees nothing: C and D each keep a count of one. Mark and sweep marks A, B and E, and sweeps C and D. Then it tries the real thing. Python mostly uses reference counting, with a separate tracing collector to catch cycles. A real cycle stays alive after the program deletes both names. It disappears only when gc dot collect runs.

Trade-Off

Why Python Uses Both Methods

Tracing collectors have a price, though. To walk the objects, they must pause the program, or share time with it. Reference counting frees memory the moment it's garbage, but misses cycles. That's why Python uses both.

Quick Check

What Mark and Sweep Frees

Quick check, with a new heap. P and Q point at each other. R points to S. The program holds only R. Which objects does mark and sweep free? Pause, and decide. P and Q. The walk starts at the root, R, and marks R and S. Nothing leads from them to P or Q, so the sweep frees both. Nothing is reference counting's answer, since P and Q keep each other's count at one. And R and S are exactly what stays. The program agrees. Here's the new heap, ready to run. Counting frees nothing. The walk marks R and S, and the sweep frees P and Q. And the real Python cycle at the end behaves as before: only gc dot collect frees it.

Real Case

Sam's Shelf Revisited

Back to Sam's shelf. Picking a gap is the fit rule. The awkward leftover gaps are external fragmentation, and sliding the boxes together is compaction. And clearing away what nobody will use again is the garbage collector's job.

Key Takeaways

Holes, Heaps and Collectors

To recap. First fit, best fit and worst fit choose a hole, and no rule wins every time. External fragmentation is waste between blocks, which compaction fixes. Internal fragmentation is waste inside a block. In C, malloc and free manage the heap by hand: check for NULL, and free each block exactly once. And garbage collectors free unreachable objects, by reference counting, or by mark and sweep.

About Introduction to Operating Systems at UPI Study

Introduction to Operating Systems (Computer Science 354) is a self-paced online course of 83 video lessons in 10 chapters, from what an operating system does and process scheduling to concurrency, memory, devices, file systems, networks, the internet, security and virtual machines. 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: Linux vs Operating Systems

Why take it here

Why students take Introduction to Operating Systems with UPI Study

What happens under every app you runIntroduction to Operating Systems explains the software that runs a computer: processes and scheduling, threads and synchronization, deadlock, memory and paging, devices and storage, file systems, networking, security and virtualization. It suits computer science and information technology degrees.
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

Introduction to Operating Systems 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 Memory Allocation and Garbage Collection

What is the difference between first fit, best fit and worst fit?
First fit places a request in the first free hole that is big enough, best fit chooses the smallest hole that fits, and worst fit chooses the largest hole. First fit is quick to search, while best fit must look through every hole. For a 160 KB request with holes of 300, 150, 700 and 180 KB, first fit picks 300, best fit picks 180, and worst fit picks 700.
What is the difference between internal and external fragmentation?
External fragmentation is free memory split into holes between blocks that are each too small to use, while internal fragmentation is unused space inside a block that was handed out. If memory is handed out in 100 KB blocks, a 212 KB request takes three blocks and wastes 88 KB inside them. Compaction cures external fragmentation by sliding programs together so the holes merge.
What are common mistakes when using malloc and free in C?
Common mistakes include skipping the NULL check, forgetting to free, freeing a block twice, and using memory after freeing it. Because malloc returns NULL when it cannot allocate, the result should be checked before use. A missing free causes a memory leak, while a double free or a use after free can crash the program or corrupt data. Setting a pointer to NULL after freeing helps catch accidental reuse.
Why can't reference counting collect cycles?
Reference counting cannot collect cycles because objects that point to each other keep each other's count at one, even when the program can no longer reach them. Tracing collectors such as mark and sweep start from the roots, mark every reachable object, and sweep the rest, so unreachable cycles are freed. Python combines both: reference counting for most objects, plus a separate tracing collector that gc.collect can run on demand.

About the Introduction to Operating Systems course

How many college credits is Introduction to Operating Systems?
Introduction to Operating Systems (Computer Science 354) 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 Introduction to Operating Systems cost and what is included?
$250, paid once, with lifetime access: all 83 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 Introduction to Operating Systems take?
It is self-paced with no deadlines. The 83 lessons total about 10 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 Introduction to Operating Systems.

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

Updated

Introduction to Operating Systems
3 credits · NCCRS
Enroll →