So, I have 2 pieces of code, one that works and one that doesn’t. The first piece was just a test to find out if a char pointer would remain valid after it is returned from a local allocation. For some reason this works:
char* test(){
char* rawr="what";
return rawr;
}
But this one doesn’t work:
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;
}
I bet that there is a better way to accomplish this task of removing the file name from the full path but for now I’m just trying to figure out why this char pointer gets deleted while the other one doesn’t. If I had to guess I would say its because I declared it differently, or because its larger. Yes, I could just pass another char pointer as an argument to this function, but that wouldn’t answer my question.
The string literal
"what"is not allocated on the stack – it remains valid throughout the life of the program. However it must NOT be modified. The pointerrawritself is on the stack, but this is only a problem if you write things like&rawr, getting a pointer-to-a-pointer.This, however, puts an array on the stack.
retthere is implicitly&rett[0], that is, gets a pointer to the first element of the array, which is very much on the stack, and is invalid after returning.