Original article: http://www.cnblogs.com/madengwei/archive/2008/02/18/1072410.html
[]C ++
("Wildpointer)
Class Object {public: Object (void) {std: cout <"Initialization" <std: endl ;}~ Object (void) {std: cout <"Destroy" <std: endl;} void Initialize (void) {std :: cout <"Initialization" <std: endl;} void Destroy (void) {std: cout <"Destroy" <std: endl ;}} void UseMallocFree (void) {Object * ip = (Object *) malloc (sizeof (Object); // apply for dynamic memory ip-> Initialize (); // initialization //... Ip-> Destroy (); // clear free (ip); // release memory} void UseNewDelete (void) {Object * ip = new Object; // apply for dynamic memory and initialize //... Delete ip; // clear and release memory}
void Func(void){ A *a = new A; if(a == NULL) { return; } …}
void Func(void){ A *a = new A; if(a == NULL) { std::cout << “Memory Exhausted” << std::endl; exit(1); } …}
Class A {public: void Func (void) {std: cout <"Func of class A" <std: endl ;}; void Test (void) {A * p; {A a; p = & a; // note the life cycle of a} p-> Func (); // p is A "wild pointer "}
Void GetMemory (char * ip, int num) {ip = (char *) malloc (sizeof (char) * num);} void Test (void) {char * str = NULL; getMemory (str, 100); // str is still NULL strcpy (str, "hello"); // running error}
Void GetMemory (char ** p, int num) {* ip = (char *) malloc (sizeof (char) * num);} void Test (void) {char * str = NULL; GetMemory (& str, 100); // note that the parameter is & str, not str strcpy (str, "hello"); std :: cout <str <std: endl; free (str );}
Apply for dynamic memory with pointer to pointer
Of course, we can also use function return values to transmit dynamic memory. This method is simpler, as shown in the following example:
char *GetMemory(int num){ char *ip = (char *)malloc(sizeof(char) * num); return ip;}void Test(void){ char *str = NULL; str = GetMemory(100); strcpy(str, "hello"); std::cout<< str << std::endl; free(str);}
Char * GetString (void) {char p [] = "hello world"; return p; // the compiler will warn} void Test (void) {char * str = NULL; str = GetString (); // str content is spam std: cout <str <std: endl ;}