"C Program Design" rectification version 4th for the lifetime scope of the auto variable is described, including memory management and release, stating that "after the function is finished, automatically release the memory units occupied by the automatic variable"
After the function is finished, the automatic variable is freed, even if it is returned as a pointer, and the pointer address does not change when returned, but any read operation flushes the memory to an unpredictable state
If you use a function return value, you can request memory using malloc, and return when the operation is complete
The code and operation results are as follows:
1 //CUITestingCPP.cpp: Defines the entry point of the console application. 2 //3 4#include"stdafx.h"5#include <iostream>6 using namespacestd;7 8typedefstructCvhistogra9 {Ten inttype; One float**Thresh2; A intAAs; - } - Cvhistogra; the -Cvhistogra *createhist () - { - Cvhistogra Hist_value; +Hist_value.type =2; -cout <<"hist_value variable Address:"<< &hist_value <<Endl; +cout <<"Hist_value The value of the member type:"<< Hist_value.type <<Endl; A return&Hist_value; at } - -Cvhistogra *mallochist () - { -Cvhistogra * Hist_value = (cvhistogra*)malloc(sizeof(Cvhistogra)); -Hist_value->type =5; incout <<"hist_value variable Address:"<< Hist_value <<Endl; -cout <<"Hist_value The value of the member type:"<< Hist_value->type <<Endl; to + returnHist_value; - } the * int_tmain (intARGC, _tchar*argv[]) $ {Panax NotoginsengCvhistogra *histtest; -Histtest =createhist (); the +cout <<"Histtest The value of the member type:"<< Histtest->type <<Endl; Acout <<"the value of the Histtest member type is then output once the value is changed:"<< Histtest->type <<Endl; thecout <<"Histtest The value of the pointer:"<< histtest <<Endl; + - //Free (histtest);//The memory pointed to by Histtest is not created by malloc and is memory on the stack, so using free to release the failure $ $cout <<Endl; -cout <<Endl; - theCvhistogra *mallhist; -Mallhist =mallochist ();Wuyicout <<"Mallhist The value of the pointer:"<< mallhist <<Endl; thecout <<"Mallhist The value of the member type:"<< Mallhist->type <<Endl; -cout <<"Mallhist The value of the member type:"<< Mallhist->type <<Endl; Wu -mallhist->aas=9; About $ Free(mallhist); -Mallhist = NULL;//The release is set to NULL, otherwise the bottom line can also be output, but the output is the wrong value - //cout << "mallhist member Type value:" << mallhist->type << Endl; - ASystem"Pause"); + the return 0; -}
Discussion on the lifetime and scope of automatic variable and open memory