<分区>
#include <iostream>
#include <string.h>
using namespace std;
/*
The functions defined below are attempting to return address of a local
variable and if my understand is correct...the main function should be
getting garbage.
*/
int *test1(){
int a[2]={1,2};
return a; //returning address of a local variable - should not work.
}
char *test2(){
char a[2]={'a','b'};
return a; //returning address of a local variable - should not work.
}
char *test3(){
char a[1];
strcpy(a,"b");
return a; //returning address of a local variable - should not work.
}
char *test4(){
char a[2];
strcpy(a,"c");
return a; //returning address of a local variable - should not work.
}
int main()
{
int *b= test1();
cout<<*b<<endl; //gives back garbage.
char *c=test2();
cout<<*c<<endl; //gives back garbage.
char *d=test3();
cout<<*d<<endl; //this works - why?
char *e=test4();
cout<<*e<<endl; //gives back garbage.
return 0;
}
就我对函数调用和内存管理的理解而言,这个示例程序让我感到困惑。如果我理解正确,那么 b=test1() 和 c=test2() 不起作用的原因是因为它们试图返回局部变量的地址,一旦堆栈内存弹出函数,这些变量就会被删除。但为什么 d=test3() 有效?