Local variables, parameter variables are stored in the stack, and when out of scope, the allocated memory is automatically reclaimed by the system outside the scope of the action.
New memory space is stored in the heap, is not managed by the scope, is not automatically reclaimed by the system, and frees up memory only when delete is used or the entire program ends.
Therefore, it is easy to forget the delete and cause a memory leak event. For example, in a function, you define:
A * a=new a ();
Pointer A will be destroyed after the function has finished running, but new memory will not be destroyed and delete a must be executed before it can be destroyed.
In addition to the static variable, the lifetime of the global variable is the entire program run time.
The smart pointer, in the case of a pointer being destroyed, destroys the memory pointed to by the pointer, preventing a memory leak from occurring.
This is a common case of memory leaks. Try to avoid manually managing pointers, using shared_ptr and unique_ptr in c++11 to manage them.
For more information, please refer to: 51965221
About the storage location and memory recovery mechanism of local variables and global variables in C + +