I don't understand why when I call a level-1 pointer as a function parameter, I cannot set myp1 = NULL, and myp1null.
The nature of the reason for generating a wild pointer: pointer variables and memory space variables are two different concepts.
Solution: Three Steps
1. When defining a pointer, assign the pointer variable to NULL.
2. When releasing the memory, first determine whether the pointer variable is NULL.
3. After the memory is released, copy the pointer variable to NUL again.
# Define _ CRT_SECURE_NO_WARNINGS
# Include <stdlib. h>
# Include <string. h>
# Include <stdio. h>
// You have to release the second-level pointer when allocating the memory above.
Int getMem_free (char ** myp1)
{
Char * tmp1 = NULL;
If (myp1 = NULL)
{
Return-1;
}
Tmp1 = * myp1;
Free (tmp1); // release the memory space caused by pointer Variables
Tmp1 = NULL; // change the real parameter to NULL
Return 0;
}
// Level 1 pointer Method
Int getMem_free0 (char * myp1)
{
If (myp1 = NULL)
{
Return-1;
}
Free (myp1); // release the memory space caused by pointer Variables
// Do not understand here
// Myp1 = NULL ;//???
Return 0;
}
Int main0801 ()
{
Int ret = 0;
Char * p1 = NULL;
Int len1 = 0;
Char * p2 = NULL;
Int len2 = 0;
Ret = getMem (& p1, & len1, & p2, & len2 );
Printf ("p1: % s \ n", p1 );
Printf ("len1: % d \ n", len1 );
Printf ("p2: % s \ n", p2 );
Printf ("len2: % d \ n", len2 );
// GetMem_free (& p1); // release the memory
// GetMem_free (& p2 );
GetMem_free0 (p1); // In the called function, release the memory pointed to by p1, but the real parameter p1 cannot be changed to NULL. A wild pointer occurs.
GetMem_free0 (p2 );
// It is found that the above myp1 = NULL; causes p1 and p2 to generate wild pointer printing and garbled characters will appear.
Printf ("p1: % s \ n", p1 );
Printf ("len1: % d \ n", len1 );
Printf ("p2: % s \ n", p2 );
Printf ("len2: % d \ n", len2 );
System ("pause ");
Return 0;
}