不了解示例中的行为 - strcpy() 和返回本地数组地址的函数
Don't understand the behavior in the example - strcpy() and function returning address of local array
#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,也就是你真正想要发生的事情。
相关文章:
- 从 C++ 中的函数返回数组地址问题
- 打印字符数组地址的正确方法
- 在C++中为零大小的分配返回唯一地址背后的基本原理是什么?
- 字符数组地址和整数数组地址
- 从函数返回变量地址时如何修复"与局部变量关联的堆栈内存地址"?
- 为什么在递增后使用 [] 运算符访问指针数组会返回错误地址的当前内存位置
- 将对象强制转换为 dlsym 返回的地址
- C++返回静态数组地址的函数
- C++ 在 64 位平台中传递字符数组地址
- 获取字符数组地址,然后转换为指针字符
- 替换WCHAR_T错误返回存储地址
- C 11 REGEX表达不会像预期的那样返回组
- 数组中的值之和返回内存地址,除非sizeof(array)/2
- 如何指向实际元素而不仅仅是数组地址
- 如何从采用 int 和 struct 类型的指针的函数中取消引用指针返回的地址?
- 如何使用数组地址反转数组
- 函数从堆栈返回的地址是什么
- 使用指针数组中的对象调用重载的友元 ostream 插入运算符将返回内存地址
- 不了解示例中的行为 - strcpy() 和返回本地数组地址的函数
- C++套接字 - 从结构数组返回单个地址信息