// ----------------------------------------------- char * GetMemory2( void ){ char p[] = " hello world " ;return p;} void Test2( void ){char * str = NULL;str = GetMemory2(); printf(str);} // ----------------------------------------------- void GetMemory3( char ** p, int num){* p = ( char * )malloc(num);} void Test3( void ){char * str = NULL;GetMemory3( & str, 100 );strcpy(str, " hello " ); printf(str); } // ----------------------------------------------- void Test4( void ){char * str = ( char * ) malloc( 100 );strcpy(str, " hello " );free(str); if (str != NULL){strcpy(str, " world " ); printf(str);} }
// -----------------------------------------------/* What is the result of running the test1 function? A: The program crashes. Because getmemory cannot pass dynamic memory, STR in the test function is always null. Strcpy (STR, "Hello World"); will crash the program. */Test1 (); // ------------------------------------------------- // what kind of results will the function run? //// A: It may be garbled. //// Because getmemory returns a pointer pointing to the "stack memory", // the address of this pointer is not null, but its original content has been cleared, and the new content is unknown. Test2 (); // ------------------------------------------------- // what kind of results will the function run? //// A: //// (1) Hello // (2) Memory leakage test3 (); // ----------------------------------------------- // What is the result of running the test function? /// Answer: tampering with the content in the dynamic memory area is unpredictable and dangerous. //// Because free (STR); then, STR becomes a wild pointer, /// if (STR! = NULL) the statement does not work. Test4 ();//-----------------------------------------------
Source Address: http://www.cppblog.com/mzty/archive/2006/07/07/9536.html