A local variable is stored in the stack area, and the memory space is freed after the function call ends.
#include"stdio.h"; #include"stdlib.h";int*Getnum () {inti = -; return&i;}voidMain () {int*i =Getnum (); printf ("%d\n\r", i);//memory released, incorrect result}
The second malloc (memory allocate) dynamically allocates the ram in the heap area, requiring the call free to manually release.
the memory requested by malloc can be freed with free. Local variables are released with free and will error.
#include"stdio.h"; #include"stdlib.h";Char*GetColor () {void*str =malloc(4); Char*color = (Char*) str; *color++ ='R'; *color++ ='e'; *color++ ='D'; *color =' /';//String end tag return(Char*) str;}voidMain () {Char*color =GetColor (); printf ("%s\n\r", color); Free(color); printf ("%s\n\r", color);//memory released, incorrect result}
C language Stack area, heap area