Memory leak: ① access to freed memory
② access to memory without permissions
Wild pointer: A pointer to memory freed of memory or memory that does not have access rights.
There are 3 main causes of "wild pointer":
(1) The pointer variable has not been initialized. Any pointer variable that has just been created does not automatically become a null pointer, and its default value is random, and it can be scrambled. Therefore, the pointer variable should be initialized at the time it is created, either by setting the pointer to null or by having it point to legitimate memory. For example
char *p = NULL;
Char *str = new char (100);
(2) The pointer p is not set to null after being free or delete.
(3) The pointer operation goes beyond the scope of the variable. This is an impossible situation and the sample program is as follows:
Class A
{
Public
void Func (void) {cout << "Func of Class A" << Endl;}
};
void Test (void)
{
A *p;
if (...)
{
A A;
p = &a; Note the lifetime of a
}
P->func (); P is "wild pointer"
}
How to avoid wild pointers:
First, initialize the pointer
① initializes the pointer to null.
char * p = NULL;
② allocates memory with malloc
char * p = (char *) malloc (sizeof (char));
③ the pointer with a valid, accessible memory address.
Char num[30] = {0};
char *p = num;
Second, after the pointer is used up to free memory, the pointer assigned null.
Delete (p);
p = NULL;
Note:
After the malloc function has allocated memory, you should note:
① checks whether the assignment succeeds (if the assignment succeeds, returns the first address of the memory, the assignment is unsuccessful, and returns NULL.) Can be judged by the IF statement)
② empty in-memory data (there may be garbage values in malloc allocated space, empty memory with memset or bzero functions)
void bzero (void *s, int n);
S is the starting address of the space that needs to be zero, and n is the number of bytes of data to set zero.
void memset (void *start, int value, int size);
If the first address to empty space is p,value, size is the number of bytes.