Managing and using virtual memory can be a difficult and error-prone task for the C programmers. Memory-related bugs are among the most frightening because they often manifest themselves at a distance, in both time and space, from the source of the bug. Write the wrong data to the wrong location, and your program can run for hours before it finally fails in some distant part of the program. We conclude our discussion of virtual memory with a discussion of some of the common memory-related bugs.
1. Dereferencing bad pointers: Attempting to dereference a pointer into one of the large holes in the virtual address space of a process that are not mapped to any meaningful data or write to one of read-only areas of virtual memory.
2. Reading uninitialized memory: While .bss memory locations (such as uninitialized global C variables) are always initialized to zeros by
the loader, this is not true for heap memory. A common error is to assume that heap memory is initialized to zero.
3. Allowing stack buffer overflows: A program has a buffer overflow bug if it writes to a target buffer on the stack without examining the size of the input string.
4. Assuming that pointers and the objects they point to are the same size.
5. Making off-by-one errors: Initializing n+1 of the elements of ann-element array, in the process overwriting some memory that follows the array.
6. Referencing a pointer instead of the object it points to: If we are not careful about the precedence and associativity of C operators, then we incorrectly manipulate a pointer instead of the object it points to.
7. Misunderstanding pointer arithmetic: Another common mistake is to forget that arithmetic operations on pointers are performed in units that are the size of the objects they point to, which are not necessarily bytes.
8. Referencing non-existent variables: Naive C programmers who do not understand the stack discipline will sometimes reference local variables that are no longer valid.
9. Referencing data in free heap blocks: A similar error is to reference data in heap blocks that have already been freed.
10. Introducing memory leaks: Memory leaks are slow, silent killers that occur when programmers inadvertently create garbage in the heap by forgetting to free allocated blocks.