When dealing with pointers and dynamically allocated memory, there are a few common mistakes that are worth noting.
1) Dangling pointers
Dangling pointers are pointers that have not been initialize or have already been deleted. The common theme is the pointer does not point to a valid object or memory that the program owns. Writing to this type of pointers is dangerous as it can crash the program or cause trouble in processes since it can write to unexpected places. To resolve this type of error, the ideal way is to use classes when using dynamic memory and always remember to initialize the pointer to nullptr, allocate memory in the constructor, and delete/free the memory in the destructor. In C++14, there are smart pointers which make the process even easier.
The only place is in C and embedded programming, we often see code that takes precautions such as:
char * ptr = malloc(n);
if (!ptr) {
// log error and exit function
}
// function body
// do something with pointer
if (ptr) {
free(ptr);
ptr = NULL;
}
2) Memory Leaks
Memory leaks are just as they sound, forgetting to release memory resulting in memory gradually "leaking" away. This can cause the program to run out of memory and crash, or cause the computer to freeze/slow as its resources are gradually used up. The best way to resolve this is to have good pointer management, either by using classes or smart pointers.