use a pointer to do a function return value
1. When using the pointer as the return value of the function, the char *p at the main function will get the value of the calling function char *pf, that is, an address value, such as oxAE72. At this point we need to note whether the address value points to the existence of the space (that is, the operating system declaration has been registered, will not be released, that may be modified by other operations);
2, the use of stack memory return pointer is obviously wrong, because stack memory will be automatically released after the call, so that the main function to use the address space will be very dangerous.
3. It is correct to use the heap memory return pointer, but note that a memory leak problem may occur and release the memory in the main function after use.
The address that the P pointer refers to is not in the stack area (memory in the stack area is automatically released by the compiler, and the heap area is released by the system when the programmer or program ends)
Note: You cannot use free if you are not using malloc.
#include <stdio.h>
#include <stdlib.h>
char* getmemory ()
{
//char p[] = "HI";
Char *p= (char *) malloc (sizeof (char));//"Hello World";
return p;
}
int main ()
{
char *str = getmemory ()//Error! Get a piece of freed memory
printf ("\naddress of function display is%u", str);
free (str);
Str=null;
return 0;
}
After free you need null, just a habit, as long as you can guarantee that free will not continue to use after the line.
Set to null immediately after free, if the program is accidentally used, it will be killed immediately. However, if you do not set NULL, you may have a variety of strange problems if you use it accidentally.
Free is null, just a habit.
Free (p) post-pointer problem