P-3.4 Dynamic Memory, and Leaks
You can allocate and release memory correctly, explain what a leak, a double free and a use-after-free are, and use a tool that detects all three.
When the size or the lifetime of something is not known while compiling, you ask for memory at run time and become responsible for giving it back. Every ownership convention in every later language is an attempt to automate this. Doing it by hand once, and watching a tool report exactly where a leak came from, makes garbage collection and reference counting feel like solutions to a problem you have actually met.
Work through these
Requesting memory at run time, and checking whether you got it
An allocation returns an address or nothing at all, and code that assumes success will follow a null pointer on the day the machine is under pressure. The check costs one line.
Releasing memory exactly once, and who owns it
Every allocation needs one matching release, which means deciding for each piece of storage which part of the code is responsible for it. Ownership written down beats ownership assumed.
Leaks: memory that is never given back
A leak does no visible harm in a program that exits quickly and kills anything long-running. This is why servers fall over after four days rather than immediately.
Double free and use-after-free
Releasing the same storage twice, or reading it after release, corrupts the bookkeeping the allocator relies on. The crash usually happens somewhere else entirely, which is what makes these so unpleasant to chase.
Run a memory checker over a program you wrote, and read its report
A checking tool reports the exact line where leaked storage was requested and where invalid access happened. Using one on your own small program is the fastest way to trust the tool later.
CS50x: Introduction to Computer Science · Course
Sign in to keep your progress.
Free resources
We haven't checked most of these for screen reader use yet.
Links last checked 31 Aug 2026.
Stuck here?
Ask a mentor. A real person answers, and they can see exactly which topic you're on. Usually within a couple of working days.
Checking your session…
Topics shown in module order.