What decides to deallocate a local allocation on return?
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 fin开发者_如何学Pythond 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.
rett is allocated on the stack so when the method returns it's memory space is no longer valid.
rawr points to a literal which your compiler likely reserves in (read-only) memory when the program runs.
Both approaches are wrong.
You need to allocate the buffer using new (or malloc in C) or use std::string.
char* test(){
char* rawr="what";
return rawr;
}
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 pointer rawr
itself is on the stack, but this is only a problem if you write things like &rawr
, getting a pointer-to-a-pointer.
char* folderfromfile(char* filz){ //gets the folder path from the file path
int lastslash=-1,i=0;char rett[256]; //declarations
///// ...
return rett;
}
This, however, puts an array on the stack. rett
here 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.
精彩评论