I came across some legacy code that contains a function like this:
LPCTSTR returnString()
{
char buffer[50000];
LPCTSTR t;
/*Some code here that copies some string into buffer*/
t = buffer;
return t;
}
Now, I strongly suspect that this is wrong. I tried calling the function and it does return the string you expect it to return. However, I don’t really see how that happens: isn’t the char array supposed to be stored on the stack, and thus deallocated after the function exits? If I’m wrong, and it gets stored on the heap, isn’t this function creating a memory leak?
Your code is exhibiting undefined behaviour – in this case, the UB is that it appears to “work”. If you want the array stored on the heap, you need to allocate it with new[]. The caller of the function will then be responsible for deleting it via the pointer the function returns.