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

标签 c++ function pointers strcpy

<分区>

#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() 有效?

最佳答案

你倒霉了,因为程序没能炸毁。

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

有人会建议您将编译器警告级别调到最高级别。大多数编译器会礼貌地至少给您一条警告消息。

关于c++ - 不理解示例中的行为 - strcpy() 和函数返回本地数组的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735431/

相关文章:

python - 在另一个函数中调用一个函数

javascript - javascript函数中的所有语句都没有被执行

c++ - 访问数组内容时出错

c++ - WriteFile 失败超过 4700 个 block (SD 卡原始写入/窗口)

php - 从 PHP-CPP 的 Php::Value 中检索类名

C++ 更改字符串函数中的小写字母(再次......)

c - 指针大小相同吗?

c++ - 模板 vector <typename>迭代器的NULL/默认值

c++ - 相同大小的二维和一维数组之间的内存或执行问题?

c - 如何在c中的某个位置终止字符指针?