gpt4 book ai didi

c++ - 是什么决定在返回时取消分配本地分配?

转载 作者:行者123 更新时间:2023-11-27 22:29:22 25 4
gpt4 key购买 nike

因此,我有 2 段代码,一段有效,一段无效。第一部分只是一个测试,以确定 char 指针在从本地分配返回后是否仍然有效。出于某种原因,这有效:

    char* test(){
char* rawr="what";
return rawr;
}

但是这个不行:

    char* folderfromfile(char* filz) //gets the folder path from the file path
{
//declarations
int lastslash=-1;
int i =0;
char rett[256];

for(i;(int)filz[i]!=0;i++)
if(filz[i]=='\\')
lastslash=i; //records the last known backslash

if(lastslash==-1)
return ""; //didn't find a backslash

for(i=0;i<=lastslash;i++)
rett[i]=filz[i]; // copies to new string

rett[i] =0; //end of string
cout << &rett << "====" << rett << endl;

system("pause>nul");//pause so i can watch over the memory before it deallocates
return rett;
}

我打赌有更好的方法来完成从完整路径中删除文件名的任务,但现在我只是想弄清楚为什么这个字符指针被删除而另一个没有。如果我不得不猜测,我会说它是因为我声明它的方式不同,或者因为它更大。是的,我可以将另一个 char 指针作为参数传递给该函数,但这不能回答我的问题。

最佳答案

rett 分配在堆栈上,因此当方法返回时,它的内存空间不再有效。

rawr 指向一个文字,您的编译器可能会在程序运行时将其保留在(只读)内存中。

这两种方法都是错误的。

您需要使用 new(或 C 中的 malloc)或使用 std::string 分配缓冲区。

关于c++ - 是什么决定在返回时取消分配本地分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4761605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com