Precautions for using free functions in C Language

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.