c*******t 发帖数: 1095 | 1 小公司不是亚马逊
第一题:
char* foo(char *s1){
char s2[32];
strcpy(s2,s1);
return s2;
}
int main()
{
char * t;
t=foo("hello");
printf("%s\n",t);
return 0;
}
问有啥问题,为什么?
没答出来,直接被拒鸟 |
S**I 发帖数: 15689 | 2 1. s2 is a local variable
2. s2 has type char* const
【在 c*******t 的大作中提到】 : 小公司不是亚马逊 : 第一题: : char* foo(char *s1){ : char s2[32]; : strcpy(s2,s1); : return s2; : } : int main() : { : char * t;
|
c*******t 发帖数: 1095 | 3 上机试试,看看打印出来的是什么?
【在 S**I 的大作中提到】 : 1. s2 is a local variable : 2. s2 has type char* const
|
s********k 发帖数: 6180 | 4 S2 is local variable, but not const char.
【在 S**I 的大作中提到】 : 1. s2 is a local variable : 2. s2 has type char* const
|
S**I 发帖数: 15689 | 5 char* const
【在 s********k 的大作中提到】 : S2 is local variable, but not const char.
|
S**I 发帖数: 15689 | 6 return address of a local variable is undefined behavior, so theoretically
could be anything.
【在 c*******t 的大作中提到】 : 上机试试,看看打印出来的是什么?
|
S**I 发帖数: 15689 | 7 just tested, here are the output results:
1. Visual Studio 2008:
debug mode: some garbage
release mode: "hello"
2. Intel C++ compiler: "hello"
3. GCC: nothing
BTW, all three compilers give "return address of a local variable" like
warning.
【在 c*******t 的大作中提到】 : 上机试试,看看打印出来的是什么?
|
s********k 发帖数: 6180 | 8 VC怎么把这个local 的指针返回的?
【在 S**I 的大作中提到】 : just tested, here are the output results: : 1. Visual Studio 2008: : debug mode: some garbage : release mode: "hello" : 2. Intel C++ compiler: "hello" : 3. GCC: nothing : BTW, all three compilers give "return address of a local variable" like : warning.
|
S**I 发帖数: 15689 | 9 I guess t just happens to point to the same memory block that s2 was
allocated.
【在 s********k 的大作中提到】 : VC怎么把这个local 的指针返回的?
|
s********k 发帖数: 6180 | 10 这个可能几乎为0吧,否则这个编译器也太差了,很容易被利用buffer overflow啊?
【在 S**I 的大作中提到】 : I guess t just happens to point to the same memory block that s2 was : allocated.
|
z****u 发帖数: 24 | 11 除了s2是一个local variable以外,另一个问题是如果s1的长度大于32,则会buffer
overflow,有可能覆盖返回地址 |
S**I 发帖数: 15689 | 12 估计是这样:s2分配在stack上,对foo的调用结束时s2被deallocate,但是s2被分配的
那段内存还没有被覆盖,对t的赋值导致在stack上为t分配内存,于是t就指向了s2原先
指向的内存地址。
我觉得几乎不可能被利用,按标准来说这是undefined behavior,返回任何结果都是有
可能的,也包括正确的结果——但是这个不可能被事先预料到。
【在 s********k 的大作中提到】 : 这个可能几乎为0吧,否则这个编译器也太差了,很容易被利用buffer overflow啊?
|