Memory articles - points to the stack memory pointer

Original Address: HTTP: // blog.csdn.net/ipmux/article/details/17549157 


running below what kind of results? 

    char * the GetString ( void ) 

    { 

      char Array [ . 6 ]; 

      strcpy (Array, "Hello"); 

      return Array; 

    } 

    void main () 

    { 

      char * pstr = NULL; 

      pstr = the GetString (); 

      the printf ( " % S \ n- " , pstr); 

    } 

    answer this question, his mind must have a string that stack memory contents such as" flash in the pan ", its effective life cycle is only equal to the function of the period, access to the stack memory is a prerequisite for running range function the, once the function exits, the respective stack memory immediately dissipated as elusive, then access is "illegal" wild pointer operation. 

    In the embodiment, the function char* GetString returns point to a local array Array [ 6 ] pointer, but Array [ 6 ] located in the stack, the stack memory function fails immediately after its end, the function exits and then attempts to become an illegal operation by pstr access the stack memory. Therefore, this mechanism returns a pointer pointing to the stack memory, it seems to continue to access the stack memory after the function exits left a "back door" is actually a subtle trap. Then compare the following example: 

    char * the GetString ( void ) 

   { 

      char Array [ . 6 ] = "Hello"; 

      char * P = the malloc ( . 6 ); 

      strcpy (P, Array); 

      return P; 

    } 

    void main () 

    { 

      char * STR = NULL; 

      STR = the GetString (); 

      the printf ( " % S \ n- " , STR);

    } 

    Here string from the hello first Array [] where the copied to the stack memory pointer p pointing to heap memory, when after GetString function, Array [] stack memory fails, but the heap memory is still valid referring to the pointer p and save the "hello" string, the function returns a pointer to the heap pointer would be no problem. If it directly with a pointer to a string: 

    char * the GetString ( void ) 

    { 

      char * P = " Hello " ; 

      return P; 

    } 

    void main () 

    { 

      char * STR = NULL; 

      STR = the GetString (); 

      the printf ( " % S \ n- " , STR); 

    } 

    the original pointer to the array to be modified, i.e. char * STR = " Hello " , this is also possible, as " hello "String constant data area is located, is still valid after the sub-functions can still be read by this memory pointer returned p . 

     The main stack itself is still maintained by the compiler and management, so under normal circumstances the program should be avoided pointing the stack pointer

 

Guess you like

Origin www.cnblogs.com/Stephen-Qin/p/11681431.html