Introduction to free functions and wild pointers in C Language

Source: Internet
Author: User

The following is a detailed analysis of the free function and wild pointer in C language. For more information, see

[From msdn & encyclopedia]
Prototype: void free (void * ptr );
# Include <stdlib. h> or # include <malloc. h>
Deallocate space in memory
Release the bucket to which the ptr points. The released space is usually sent to the available storage zone pool. You can call the malloc, realloc, and realloc functions to distribute the space in the future.
Note: If you use the free function twice in a row, an error will certainly occur. The number of malloc times must be equal to the number of free times.
A block of memory previusly allocated using a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.
If ptr does not point to a block of memory allocated with the above functions, the behavior is undefined.
If ptr is a null pointer, the function does nothing
Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location
DEMO:

Copy codeThe Code is 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 % sn", str );
/* Free memory */
Free (str );
}
Getch ();
Return 0;
}
# Endif


DEMO: perror
Perror () is used to output the cause of the previous function error to the standard device (stderr ). The string referred to by parameter s is printed first, followed by the error cause string. The cause of this error is determined based on the value of the global variable errno.

Copy codeThe Code is as follows:
# Include <stdio. h>
# Include <stdlib. h> // perror is contained 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 codeThe Code is 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,, sans-serif; font-size: 13.63636302947998px; line-height: 24px; text-indent: 30px; "> the memory indicated by ptr is released, but the address indicated by ptr remains unchanged. The original memory becomes" junk "memory (unavailable memory) </span>
# If 1
If (ptr! = NULL)/* <span style = "font-family: arial,, sans-serif; font-size: 13.636302947998px; line-height: 24px; text-indent: 30px; "> error prevention </span> */
{
Strcpy (ptr, "world ");
Printf ("% sn", ptr );
}
# Endif
Getch ();
Return 0;
}


After free (str), the pointer still points to the original heap address, that is, you can continue to use it, but it is very dangerous because the operating system already thinks this memory can be used, he will assign him to other programs without consideration, so you may have been replaced by another program next time. This situation is called"Wild Pointer", so it is best to leave it blank after free ().
Str = NULL;
That is to say, this program has abandoned and used it again.
What is"Wild pointer", Here to add.
A wild pointer is a pointer that cannot be controlled by a programmer or operator. The wild pointer is not a NULL pointer, but a pointer pointing to "garbage.

The main causes of "wild pointer" are:
1. pointer variables are not initialized,
When a pointer variable is created, it does not automatically become a NULL pointer. Its default value is random, which means it is random. During initialization, either the pointer is valid or the pointer is NULL.

2. After the pointer variable is free or delete, It is not set to NULL.They only release the memory indicated by the pointer, but do not kill the pointer itself. Normally, if (p! = NULL. Unfortunately, the if statement does not prevent errors at this time, because even if p is not a NULL pointer, it does not point to a valid memory block. This is the case in the DEMO above.

3. pointer operations go beyond the scope of variables.Pay attention to its lifecycle.

[The following is a metaphor from the Forum for better understanding .]
The CRT memory management module is a manager.
Your program ("you" for short) is a guest.
The butler has a very bucket that can be used for water.
Malloc means "butler, I want XX buckets ".
The butler first checks whether there are enough buckets for you. If not, I will tell you no. If it is enough, register these buckets for use and tell you to "use them ".
Free means: "I have used up my butler, and I will pay you back !".
As for whether you need to clean the water before giving it to the butler, it is your own business. -- Whether it is cleared.
The butler will not clear the buckets you returned (if he has so many buckets, it will be no longer exhausting to clean them ). It will be handled when other applications are used.
Clear the pointer after free, just remind yourself that these buckets are no longer mine. Do not fill them with water, ^_^
If the pointer is still used after free, it is possible that the butler has already delivered these buckets to others for drinks, but you have sprayed urine into them. A good manager may express strong dissatisfaction with your behavior and kill you (illegal operations)-this is the best result. You know that you are wrong (if there is a mistake, you can change it ). Some bad butlers may be too busy. Sometimes they will punish you if they catch you for doing bad things, but sometimes they don't know where to go-this is your nightmare, I don't know when or how to do it. In any case, in this case, there may be people who need to drink urine-I don't know if it's your boss or your customer. ^_^.
So, of course, good citizens should not take up what they have provided to their housekeepers. ^_^.

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.