The project encountered a memory leak problem. As a result, it was quite painful for everyone to work hard for 10 days. So I thought about how to avoid it? Summary:
1. try to make your function just an exit (of course you can't do it, you should also try to simplify it as much as possible, we suggest using do {...} while (false) to implement an exit of the function), the advantage of this is to ensure that all memory is released at the exit of the function. Another advantage is thatProgramEasy to maintain.
2. the memory of attribute members of the class must be released in a unified manner in the class destructor, rather than in other functions of the class, of course, the applied memory should be carried out in the constructor. Reason: how easy it is to manage automatically ~
3. When using pointers, you must first judge and then use them. Note: When using new or malloc to apply for memory, you must determine whether the application is successful. Of course, in today's virtual memory technology, it can be understood that the memory space is infinite (Hard Disk + Memory), but in some special cases, the application may still fail ~
4. [1] avoid arrays and pointers crossing the border
[2] match the use of new, delete, new [] and delete [], malloc and free
[3] avoid multiple releases to the same memory
[4] avoid returning references and pointers to local variables with return
5. Avoid "wild pointer". "wild pointer" refers to the pointer pointing to "junk" memory. Cause 3: the pointer variable is not initialized; the pointer is not set to null after it is released; the pointer operation exceeds its scope.
6. You can use raiI (resource acquisition is initialization) to obtain and initialize resources. It is to use the object lifecycle to control program resources. The simplest is to apply for resources in the constructor and release resources in the destructor, in this way, we can automatically control the use of resources, but to release the resources immediately after use, it is best to define the object as a partial Block Variable!
7. Smart pointers Technology (smart pointer) is an object that stores "pointers to objects dynamically distributed (on the heap. Their behavior is similar to the built-in pointers of C ++, but they can automatically delete the objects they point to when appropriate. Smart pointers play a significant role in the face of exceptions. They can ensure the full structure of dynamically allocated objects.