Free function of C language and wild pointer introduction _c language

Source: Internet
Author: User

"From MSDN && Encyclopedia"
Prototype: void free (void *ptr);
#include <stdlib.h>/#include <malloc.h>
deallocate spaces in memory
Releases the storage space that the PTR points to. The freed space is usually fed into the pool of available storage, which can then be reassigned by invoking the malloc, realloc, and realloc functions.
Note: The free function is used two times in a row, and errors are sure to occur. The number of malloc is equal to the number of free.
A block of memory previously allocated using a call to malloc, calloc or realloc is deallocated, making it available again For further allocations.
If PTR does the memory allocated with the above functions and the behavior is undefined.
If ptr is a null pointer, the function does nothing
Notice The This function does the "not" change the value of PTR itself, hence it still points to the same (now invalid) locatio N
DEMO:

Copy Code code as follows:

#define First_demo
#define Second_demo
#ifdef First_demo
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main (void)
{
int *buffer1,*buffer2,*buffer3;
buffer1= (int *) malloc (100*sizeof (int));
buffer2= (int *) calloc (100,sizeof (int));
buffer3= (int *) realloc (buffer2,500*sizeof (int));
Free (buffer1);
Free (BUFFER3);
Getch ();
return 0;
}
#elif defined Second_demo
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main (void)
{
Char *str;
/*allocate Memory for string*/
Str= (char *) malloc (10);
if (str==null)
{
Perror ("malloc");
Abort ();
}
Else
{
/*copy "Hello" to string*/
strcpy (str, "Hello");
/*display string*/
printf ("String is%s\n", str);
/*free memory*/
Free (str);
}
Getch ();
return 0;
}
#endif

Demo:perror
Perror () is used to output the error of the previous function to the standard device (stderr). The string that the argument s refers to is printed first, followed by the error reason string. This error reason determines the string to output according to the value of the global variable errno.
Copy Code code as follows:

#include <stdio.h>
#include <stdlib.h>//perror included in this file
#include <conio.h>
int main (void)
{
FILE *FP;
Fp=fopen ("abc", "r+");
if (NULL = fp)
{
Perror ("abc");
}
Getch ();
return 0;
}

Output
Abc:no such file or directory
DEMO:
Copy Code code as follows:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
Char *ptr;
Ptr= (char *) malloc (100);
strcpy (PTR, "Hello");
Free (PTR); <span style= "font-family:arial, song body, Sans-serif; font-size:13.63636302947998px; line-height:24px; text-indent:30px; " > PTR refers to memory being freed, but the address that PTR refers to remains unchanged, and the original memory becomes "junk" memory (not available memory) </span>
#if 1
if (ptr!=null)/*<span style= "font-family:arial, XXFarEastFont-Arial, Sans-serif; font-size:13.63636302947998px; line-height:24px; text-indent:30px; " > does not play a role in error prevention </span>*/
{
strcpy (PTR, "world");
printf ("%s\n", PTR);
}
#endif
Getch ();
return 0;
}

After free (str) The pointer still points to the original heap address. That you can continue to use, but it is dangerous, because the operating system has thought that this memory can be used, he will not consider to assign him to other programs, so the next time you use may have been another program to change, this situation is called "Wild Pointer", so the best free () and then empty
str = NULL;
That this procedure has given up to use him again.
What Wild Pointer"Here to Add.
A wild pointer is a pointer that a programmer or operator cannot control. The wild pointer is not a null pointer, but a pointer to "garbage".

The cause of "wild pointer" is mainly
1. The pointer variable is not 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. Either point to a valid pointer or point to NULL when initializing.

2. After the pointer variable is free or delete, it is not set to null. They simply release the memory that the pointer refers to, but do not kill the pointer itself. The statement if (p!= NULL) is usually used for error proofing. Unfortunately, the IF statement does not work correctly, because even if p is not a null pointer, it does not point to a valid block of memory. This is the case with the demo above.

3. The pointer operation goes beyond the scope of the variable. pay attention to its life cycle.

The following is an image metaphor from the forum to deepen your understanding of the

. The memory management module of the
CRT is a housekeeper.   
Your Program ("You") is a guest.   
The Butler has a very pair of buckets that can be used to fill water.   
malloc means "housekeeper, I want xx bucket".   
The housekeeper first looks at if there is not enough bucket for you, if not, then tell you No. If enough, then register the buckets have been used, and then tell you to "use it."   
The meaning of free means: "The housekeeper I ran out, return you!" ”。   
As for whether you give the housekeeper a clean water first, then it is your own business. -is not clear zero.   
The butler will not pour the bucket you returned to dry (he has so many buckets, and every return is clean). I'll take care of it for the rest of the day anyway.   
Free to clear the pointer after zero just remind yourself that these buckets are not mine, do not finish the water, ^_^   
If free and then use the pointer, It is possible that the housekeeper has given the bucket to someone else to drink, and you have peed in it. A good housekeeper may express a strong dissatisfaction with your behavior, kill you (illegal operation)-this is the best result, you know you are wrong (change it). Some bad housekeeper may not be busy, sometimes caught you do bad to punish you, sometimes do not know where to go-this is your nightmare, do not know when and how the matter of their own death. In any case, there's a good chance that someone will drink urine--not knowing if it's your boss or your client. ^_^.   
So, of course, the good citizens return the things to the housekeeper and don't take it anymore, ^_^.

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.