1. What is memory leakage:
The heap memory space is anonymous after being created using the new statement. Therefore, you must use the pointer to record the heap memory address. Pointers are generally defined as local variables.
Since the memory space created using new is not automatically released by the system, if you do not release her, the memory in this region will never be used by other data, the pointer to the memory is a local variable. When the function defining the pointer ends and returns, the pointer disappears and we can no longer find the memory area in the block, the pointer pointing to the memory area automatically disappears. The computer will no longer be able to find the memory in the region. It is like losing the memory, which is called a memory leak.
# Include <iostream>
Using namespace STD;
Int main ()
{
Int * P = new int;
P = new int; // The memory address of the P pointer is lost for the first time, and the heap memory will never be used.ProgramAnd then use it.
Return 0;
}
This bad situation persists until the program ends the memory in this region to resume use. Therefore, if you do not need a piece of memory space, you must use the key auto Delete to release the memory pointed to by the pointer to the memory space, that is, to release the memory, this gives others the opportunity to use the memory next time without releasing the pointer, so you can also use this pointer.
2. Example:
# include
using namespace STD;
int main ()
{< br> int * P = new int;
* P = 144;
cout <"* P points to the heap memory space. After assigning a value to the memory space," cout <"* P:" <* P Delete P;
cout <"after releasing the memory space pointed to by P:" cout <"* P:" <* P P = 0;
P = new int; // be sure to remember that after the P pointer is null, if you want to use this p pointer to output * P value, you must assign a new memory space to P (using the new type name)
* P = 125;
cout <"Release the memory space pointed to by P, assign a new heap memory space to P, and assign a value to the new heap memory space" cout <"* P:" <* P return 0;
}