Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue passing C-Strings in C++

Tags:

c++

string

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();
}
like image 862
Nick Gotch Avatar asked Dec 09 '25 01:12

Nick Gotch


2 Answers

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.

like image 145
Reed Copsey Avatar answered Dec 10 '25 14:12

Reed Copsey


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().

like image 33
Jerry Coffin Avatar answered Dec 10 '25 14:12

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!