First, let's look at several error-prone problems:
(1) void GetMemory (char * p)
{
P = (char *) malloc (100 );
}
Void Test (void)
{
Char * STR = NULL;
Getmemory (STR );
Strcpy (STR, "Hello World ");
Printf (STR );
}
Result: The program crashed.
Because GetMemory cannot pass dynamic memory, str in the Test function is always NULL.
Strcpy (str, "hello world"); will crash the program.
Corrected: The GetMemory function isChar * GetMenory (char * p) {return p = (char *) malloc (100 );}
(2) char * getmemory (void)
{
Char P [] = "Hello World ";
Return P;
}
Void test (void)
{
Char * STR = NULL;
Str = GetMemory ();
Printf (str );
}
Result: It may be garbled.
Because GetMemory returns a pointer to "stack memory", the address of this pointer is not NULL, but its original content has been cleared at the end of the function, and the new content is unknown. Returns the value of a local variable, but does not return the address of a local variable. (Try not to make the return value a local variable)
Corrected: The GetMemory function isChar * GetMenory (char * p) {return p = "hello world ";}
(3) void GetMemory (char ** p, int num)
{
* P = (char *) malloc (num );
}
Void Test (void)
{
Char * str = NULL;
GetMemory (& str, 100 );
Strcpy (str, "hello ");
Printf (str );
}
Result: The output string is "hello ".
(4)Void Test (void)
{
Char * str = (char *) malloc (100 );
Strcpy (str, "hello ");
Free (str );
If (str! = NULL)
{
Strcpy (str, "world ");
Printf (str );
}
}
Result: After free (str), str becomes a wild pointer. if (str! = NULL) the statement does not work. For more information, see Introduction to the wild pointer.