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
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 Introduction to Operating Systems.
Lesson complete
Earn the 3 college credits for Introduction to Operating Systems
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Peripheral Devices →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Linux vs Operating Systems
Why take it here
Why students take Introduction to Operating Systems with UPI Study
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.
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 Memory Allocation and Garbage Collection
What is the difference between first fit, best fit and worst fit?
What is the difference between internal and external fragmentation?
What are common mistakes when using malloc and free in C?
Why can't reference counting collect cycles?
About the Introduction to Operating Systems course
How many college credits is Introduction to Operating Systems?
How much does Introduction to Operating Systems cost and what is included?
Which universities accept UPI Study credits?
How long does Introduction to Operating Systems take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →