How to prevent memory violations
If we prevent the two cases above from occurring then code you write will not crash. Third party code that you call can still crash, but we will get to how to minimize that shortly.
First, we want to prevent access to memory we do not own. Let me lay out some rules to follow:
- Pointers must be initialized when they are created, either to NULL or to valid memory.
- Deleted pointers must always be set to NULL or to valid memory on the very next line after the delete.
- Before dereferencing a pointer, you must check that it is not NULL. You can only skip this check if you checked the pointer before in the same function, and you did not call ANY function or execute any code that could access that pointer between then and now.
- Only one pointer can own a given block of memory. This means that for any block of memory there can be only one definitive pointer and all other pointers to that block of memory must be temporary and be set back to NULL as soon as possible. You cannot trust any temporary pointer to be valid between function calls or be valid once you called code in another object.
- Bounds must be checked before using an index to dereference an array pointer.