In C language, the free () function is required to release the memory segment after the dynamic allocation functions such as malloc () are used up. However, this function has a feature that after use, it does not point the pointer to null. It only tells the OS that the memory occupied by the previously malloc function can be used by other processes again, but the free pointer still points to the memory of the segment, this pointer is usually called a wild pointer.
. Pay special attention to this.
Example:
Hypothesis
Char * P = malloc (sizeof (char); then the value of P is 0x00000001.
* P = 'a'; // write 'A' to address 0x00000001 ';
Free (p); // The 0x00000001 address is no longer accessible through P. If the 0 x address is accessed through P, the operation is considered invalid.
* P = 80; // here, we use P to write 80 to address 0x00000001. As mentioned above, it is already free. This is illegal.
You
As you can imagine, after free (P) is executed, the memory address 0x00000001 is free, and the system or program is requisitioned elsewhere (for example, using malloc ).
Address 0x00000001 is used as a place to store the backup value, and a value is written to it, which is assumed to be 200, but you can use * P =
80; changed the value in address 0x00000001. The original backup is 200. If you change it to 80 illegally, then the system or program with the right to use address 0x00000001 will
An error occurs when the backup value is read, which is 200 and is now 80.
Therefore, a code rule is to convert P = NULL after free (P;
That is
Free (P );
P = NULL;
In the code, it must appear together.
To prevent * P operations.
And remember