C ++ pointer-pointer advanced-

Source: Internet
Author: User

 

// ----------------------------------------------- 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.