【发布时间】:2015-07-30 22:55:25
【问题描述】:
#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() 有效呢?
【问题讨论】:
-
没有什么“工作”。这都是未定义的行为。
-
我很困惑为什么你甚至会在 C++ 中以
char*开头。 -
FWIW,请注意
test3()也有一个错误,它写入到a[]数组的末尾之后。
标签: c++ function pointers strcpy