这样为什么不会发生访问内存失败

hackbuteer1 hackbuteer1 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#include "iostream"
#include "string"
using namespace std;

char *GetMemory( void )
{
char p[] = "hello world";
return p;
}

void Test( void )
{
char *str = NULL;
str = GetMemory();
cout<<*(str+6)<<endl; //这里可以遍历hello world这个字符串
}

int main(void)
{
Test();
system("pause");
return 0;
}

GetMemory函数内部的p数组是栈上的临时变量,函数返回后就销毁了。。
为什么下面的代码
cout<<*str<<endl;
cout<<*(str+1)<<endl;
。。。。。。
cout<<*(str+10)<<endl; 这样可以遍历输出hello world 整个字符串,这个字符串是栈上的临时变量,函数返回后就销毁了,str不应该可以访问到的啊。。
还有就是cout<<*(str+15)<<endl; 都可以输出,而且还没有编译错误,15已经远远超出了hello world的长度了啊。。
很奇怪啊。。。。
...全文

相关推荐

评论 29
收藏 已收藏
分享
返回顶部
hackbuteer1
C++ 语言 65,214 成员 250,514 内容