不了解示例中的行为 - strcpy() 和返回本地数组地址的函数

Don't understand the behavior in the example - strcpy() and function returning address of local array

本文关键字:返回 组地址 数组 函数 strcpy 不了解      更新时间:2023-10-16
#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()有效呢?

你运气不好,因为程序没有爆炸。

拷贝字符串(a,"b";in test3从根本上说是邪恶的,因为在a中有1个字符的空间,并且已知strcpy复制双引号中的一个字符,加上一个终止NUL字符,这会覆盖您的程序实际上没有分配的内存。

有人会建议你把编译器的警告级别调到最高级别。大多数编译器都会礼貌地给出至少一个警告信息。

你的第三个例子成功的原因可以总结为"月相是正确的"。

所有示例都是未定义行为,因为它们返回对局部变量的引用(或指针)。未定义的行为意味着任何事情都可能发生——包括有时候正确的事情TM,也就是你真正想要发生的事情。