Below are 3 functions. main() prints out as expected.
Now, in mycharstack() the string is stored on stack I guess, so as “ch” goes out of scope, it should not be able to return the string. How does it work correctly?
I guess the string stored in mychar() is also on stack. Is it supposed to work correctly?
I guess there are other errors in the code and memory leaks, please let me know if any. I could do these cleaner & easier with std::string. But I want to understand what’s going on with char*.
#include <iostream>
using namespace std;
char* mychar()
{
return "Hello";
}
char* mycharstack()
{
char* ch = "Hello Stack";
return ch;
}
char* mycharheap()
{
char* ch = new char;
ch = "Hello Heap";
return ch;
}
int main()
{
cout << "mychar() = " << mychar() << endl;
cout << "mycharstack() = " << mycharstack() << endl;
cout << "mycharheap() = " << mycharheap() << endl;
system("PAUSE");
return 0;
}
In C++, the string handling is different from, for example, pascal.
This does following:
char* ch = new char;creates memory for ONE character, and assigns it to variablechch = "Hello Heap";assigns to variablechpointer to readonly memory, which contains bytes"Hello Heap\0". Also, the original content of variablechis lost, resulting in memory leak.return ch;returns the pointer stored to variablech.What you probably wanted is
Note the
strcpy-> you’ve got memory inch, that has space for 11 chars, and you are filling it by string from read-only portion of memory.There will be a leak in this case. You will need to delete the memory after writing, like:
However, I highly don’t recommend doing this (allocating memory in callee and deleting in caller). For this situations, there are, for example, STL
std::string, another common and more reasonable approach is allocating in caller, passing to callee, which ‘fills’ the memory with result, and deallocating in caller again.What will result in undefined behavior is following:
This will create array on stack with bytes
"Hello Heap\0", and then tries to return pointer to first byte of that array (which can, in calling function, point to anything)