free()

c language often need to allocate memory space for a pointer variable, need to use a set of functions:
malloc () and free ()
when in use need to include the header file stdlib.h
malloc () is better understood, free () function under major concern , see the following section of code:
 
char * STR = (char *) the malloc (100);
strcpy (STR, "! Hello World");
Free (STR);
strcpy (STR, "the OK");
the printf ( "% S \ n ", str);
 
this code is tested in the machine when the output is: OK
, but the fact is that the result of this? In fact, we just fluke.
Take a closer look at the code. First, allocate memory, and then call the library function copies hello world str pointed to space, free swap str, OK then copied to str, the final output.
To know what went wrong, we must clearly know free () function in the end what has been done.
In fact, free () function simply release str pointer to memory space that is unbound pointer str relationship and that memory, but still points to a piece of str memory, while the second copy function is executed, since that memory not in use, it can complete the copy, just in case that memory is allocated, this line of code will be wrong.
Therefore, a good practice is free (rear) manually pointer to NULL, to prevent subsequent dereferencing.
 
Note that there are points in the system to remember malloc (after) is the current address and size of the allocation space, the error will be as follows
char * PTR = (char *) malloc (100);
PTR = PTR +. 1;
Free (ptr);
the reason is ptr pointer has changed.

Guess you like

Origin www.cnblogs.com/gaoshaonian/p/11389130.html