I'm not C++ developer and I'm trying to figure out why when I return a C-string from a function I'm getting garbage out.
#include <stdio.h>
const char* tinker(const char* foo);
int main(void)
{
const char* foo = "foo";
foo= tinker(foo);
printf(foo); // Prints garbage
return 0;
}
const char* tinker(const char* foo)
{
std::string bar(foo);
printf(bar.c_str()); // Prints correctly
return bar.c_str();
}
You're returning a C-string that's based on the internal memory of a std::string. However, this is being printed AFTER your bar is destructed. This memory is garbage by the time it reaches the printf(foo); line.
You're returning a pointer to a buffer internal to bar, but then you're destroying bar (and the buffer) before you use that pointer.
If you need the content of bar after the function returns, return bar instead of bar.c_str().
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