C ++ primer 4th, p249, said: Never return a pointer to a local object.
This means that the pointer to the local variable of the function is not returned.
The test program I used is:
// Filename: test. CPP <br/> # include <iostream> <br/> using namespace STD; <br/> char * func1 () <br/>{< br/> char STR [20] = "Hello, world! "; <Br/> char * T1 = STR; <br/> return T1; <br/>}< br/> char * func2 () <br/> {<br/> char * t2 = "Hello, world! "; <Br/> return T2; <br/>}< br/> int main () <br/>{< br/> cout <func2 () <Endl; <br/> cout <func1 () <Endl; </P> <p> return 0; <br/>}
I thought both functions would output an error, but I found that fuc2 () could print "Hello, world! ", Very strange. Use G ++ return. cpp-s to view the assembly code of the two functions:
. Lc0: <br/>. String "Hello, world! "// Character constant" Hello, world! "<Br/>. zero7 // 20 characters, 7 are 0 <br/>. Text <br/>. Align 2
Func1 ():
_ Z5func1v: <br/>. lfb1428: <br/> pushl % EBP <br/>. lcfi0: <br/> movl % ESP, % EBP <br/>. lcfi1: <br/> subl $40, % ESP <br/>. lcfi2: <br/> movl % GS: 20, % eax <br/> movl % eax,-4 (% EBP) <br/> xorl % eax, % eax <br/> movl. lc0, % eax // The subsequent code copies 20 characters (including 0) to the stack <br/> movl % eax,-24 (% EBP) // char * func1 () <br/> movl. lc0 + 4, % eax // {<br/> movl % eax,-20 (% EBP) // char * STR [20] = "Hello, world! "; <Br/> movl. lc0 + 8, % eax // char * T1 = STR; <br/> movl % eax,-16 (% EBP) // return T1; <br/> movzbl. lc0 + 12, % eax //} <br/> movb % Al,-12 (% EBP) <br/> movl $0,-11 (% EBP) <br/> movw $0,-7 (% EBP) <br/> movb $0,-5 (% EBP) // 20 characters copied <br/> Leal-24 (% EBP ), % eax // press the STR [0] address into % eax <br/> movl % eax,-28 (% EBP) // the pointer T1 is stored at % EBP-28, t1 = % eax, <br/> movl-28 (% EBP), % eax // return T1 placed in % eax <br/> movl-4 (% EBP ), % edX <br/> xorl % GS: 20, % edX <br/> je. l3 <br/> call _ stack_chk_fail <br/>. l3: <br/> Leave <br/> RET
The compilation source code of func2 () is very simple:
_ Z5func2v: <br/>. lfb1429: <br/> pushl % EBP <br/>. lcfi3: <br/> movl % ESP, % EBP <br/>. lcfi4: <br/> subl $16, % ESP <br/>. lcfi5: <br/> movl $. lc0,-4 (% EBP) <br/> movl-4 (% EBP), % eax <br/> Leave <br/> RET
It can be seen that in func1, the pointer returned is pointing to the address on the stack. When func1 exits, this region is released. If it still points to this region, the behavior is unpredictable;
In func2, the returned address points to the static constant area, while the static constant is readable and can be output.
It should be noted that func2 still has major problems, such:
Char * T3 = func2 (); <br/> * T3 = 'q ';
This operation will cause a running error. Because T3 refers to the static constant area.