什么决定在返回时解除分配本地分配?

Fyx*_*yxe 0 c++ variables scope memory-management

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

    char* test(){
        char* rawr="what";
        return rawr;  
    }
Run Code Online (Sandbox Code Playgroud)

但是这个不起作用:

    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;  
    }
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*ick 5

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

rawr指向程序运行时编译器可能在(只读)内存中保留的文字.

两种方法都是错误的.

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