Below code expected to print "kevin" But, it's printing garbage value. I have checked in debugger. The pointer returned by "operator char*" call is invalid. Any idea?
class Wrapper
{
private:
char* _data;
public:
Wrapper(const char* input)
{
int length = strlen(input) + 1;
_data = new char[length];
strcpy_s(_data, length, input);
}
~Wrapper()
{
delete[] _data;
}
operator char*()
{
return _data;
}
};
int main()
{
char* username = Wrapper("kevin");
printf(username);
return 0;
}
The problem is that your Wrapper
object is being constructed as a temporary and immediately destroyed. Through the operator char*
you're returning a pointer to memory that has been deleted by the Wrapper
object when it was destroyed.
To make it work:
Wrapper wrapper("Kevin");
char* username = wrapper;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With