Part 6 of 7 · 3 min read
Ownership habits
Habits that prevent the bugs
In plain words: Tools find bugs, and habits prevent them. Almost every heap bug is a question of ownership: who frees this block, and when? The simple rules:
- Every block has exactly one owner at a time, and the owner frees it exactly once. Write the owner in a comment or in the name of the function (a function called
create_ornew_returns a block that the caller owns). - After
free(p), setp = NULL. A laterfree(p)then does nothing (the standard saysfree(NULL)is allowed), and a later use fails at once with a null-pointer fault, which is easy to find. - Do not keep a copy of a pointer after the owner may free it. A second pointer to a block is an alias, and it becomes a dangling pointer when the block goes.
- Pass sizes along with pointers, and check them before each copy. Prefer
snprintfandmemcpywith an explicit length tostrcpy. - Use
callocormemsetwhen a block must start as zeros, sincemallocleaves old bytes in it. - In tests, run with ASan on. Many teams run the full test suite under ASan in every build.
Dangling pointer
A dangling pointer is a pointer that still holds the address of a block that has been freed, so any use of it is an access to memory that the program no longer owns.
Example: after free(p), the variable p still holds the old address until the program sets it to NULL.
Check yourself:
1. Why set a pointer to NULL after free?
2. What is an alias, and why is it dangerous after a free?
3. Why is strcpy a risk, and what is a safer choice?
Words you will meet
| Word | Meaning |
|---|---|
| Memory leak | A block that is never freed |
| Heap overflow | An access past the end of a block |
| Use after free | An access to a block that was freed |
| Double free | Freeing the same block twice |
| Undefined behaviour | A result that the language does not define |
| ASan | A compiler option that checks every memory access |
| Red zone | Forbidden bytes around a block |
| Shadow memory | A table that says which bytes may be accessed |
| Memcheck | The checking tool of Valgrind |
| Dangling pointer | A pointer to a freed block |
| Ownership | The rule of who frees a block |
Quick notes
- Undefined behaviour is the result of an action for which the C language places no requirement, such as a read past the end of a block or the use of.
- A memory leak is a block of heap memory that the program has allocated, no longer needs, and cannot free because it holds no pointer to it any more, or.
- AddressSanitizer (ASan) is a compiler feature that checks every memory access of a program against a table of allowed bytes, with forbidden red zones around heap blocks and around freed.
- Memcheck is the default tool of Valgrind.
- A dangling pointer is a pointer that still holds the address of a block that has been freed, so any use of it is an access to memory that the program no longer owns.