Why does calling c_str() on a function that returns a string not work?

what does c_str return
c_str in c
filename c_str
has no member named c_str
string to const char
c_str - c++ library
c_str include header

I have a function that is returning a string. However, when I call it and do c_str() on it to convert it into a const char*, it only works when I store it into another string first. If I directly call c_str() off of the function, it stores garbage value in the const char*.

Why is this happening? Feel like I'm missing something very fundamental here...

string str = SomeFunction();
const char* strConverted = str.c_str(); // strConverted stores the value of the string properly
const char* charArray= SomeFunction().c_str(); // charArray stores garbage value

static string SomeFunction()
    string str;
    // does some string stuff
    return str;

SomeFunction().c_str() gives you a pointer to a temporary(the automatic variable str in the body of SomeFunction). Unlike with references, the lifetime of temporaries isn't extended in this case and you end up with charArray being a dangling pointer explaining the garbage value you see later on when you try to use charArray.

On the other hand, when you do

string str_copy = SomeFunction();

str_copy is a copy of the return value of SomeFunction(). Calling c_str() on it now gives you a pointer to valid data.

Why does calling std::string.c_str() on a function that returns a string , A full expression is an expression that is not a subexpression of some other expression. The standard string class has a member function c_str() that returns a The output operation cout << cs might work as expected, but that  Remember that c_str() will return an empty string if no memory has been allocated for the string data. For this reason, the previous code won’t produce the expected results, but it also won’t generate any errors.

The value object returned by a function is a temporary. The results of c_str() are valid only through the lifetime of the temporary. The lifetime of the temporary in most cases is to the end of the full expression, which is often the semicolon.

const char *p = SomeFunction();
printf("%s\n", p); // p points to invalid memory here.

The workaround is to make sure that you use the result of c_str() before the end of the full expression.

#include <cstring>

char *strdup(const char *src_str) noexcept {
    char *new_str = new char[std::strlen(src_str) + 1];
    std::strcpy(new_str, src_str);
    return new_str;

const char *p = strdup(SomeFunction.c_str());

Note that strdup is a POSIX function, so if you are a platform that supports POSIX, it's already there.

Return c_str of local std::string - C++ queries, Resource not released in destructor Suspicious call to memset Description: Returning the c_str of a locally allocated std::string could cause the memory is deallocated when the std::string goes out of scope. The c_str method of std::​string returns a raw pointer to the memory const char * hello() {. In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string> header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars.

  1. The "string str" in method SomeFunction() is a local variable in SomeFunction(), and only survives inside the scope of SomeFunction();

  2. Since the return type of the method SomeFunction() is string, not a reference of string, after "return str;", SomeFunction() will return a copy of the value of str, which will be stored as a temporary value in some place of memory, after the call of SomeFunction(), the temporary value will be destroyed immediately;

  3. "string str = SomeFunction();" will store the returned temporary value of SomeFunction() to string str, actually is a copy of that value and stored to str, a new memory block is allocated, and the lifetime of str is bigger than the returned temporary value of SomeFunction(), after the ";" the call of SomeFunction() is finished, and the returned temporary value is destroyed immediately, the memory is recycled by system, but the copy of this value is still stored in str. That is why "const char* strConverted = str.c_str();" can get the right value, actually c_str() returned a pointer of the initial element of str (the first element memory address of str pointed string value), not the returned temporary value of SomeFunction();

  4. "const char* charArray= SomeFunction().c_str();" is different, "SomeFunction().c_str()" will return a pointer of the initial element of the returned temporary value (the first element memory address of returned temporary string value), but after the call of SomeFunction(), the returned temporary value is destroyed, and that memory address is reused by the system, charArray can get the value of that memory address, but not the value you expected;

Programming and Problem Solving with C++, To make the above code work correctly, we need to convert a string variable to a C The string data type provides a value-returning function named c_str that is (The original string contained in fileName is not changed by the function call.) < "Enter the input file name: "; cin >> fileName; inFile. open (fileName . c_str () ) ;  String is an array of characters. In this guide, we learn how to declare strings, how to work with strings in C programming and how to use the pre-defined string handling functions. We will see how to compare two strings, concatenate strings, copy one string to another & perform various string manipulation operations.

Use strcpy to copy the string to a locally defined array and your code will work fine.

Programming in C++, To make the above code work correctly, we need to convert a string variable The string data type provides a value-returning function named c_str that is applied to a string variable as follows: fileName. c_str () This function returns the C string (The original string contained in fileName is not changed by the function call.)  VB.net working with sql string does not work, help Cast from string "2076719" to type 'Long' is not valid; String Format help; Search for multiple things in a string; std::map<int,std::set<std::string> > Wrong? (Segmentation fault.) Iterating through a string; Learning OOP - why is string.Join static, while string.Spit is not?

Convert std::string to const char* in C++, In this post, we will discuss how to convert a std::string to const char* in C++. The returned std::string str = "std::string to const char*";. const char *c = str.c_str();. std::cout << c;. return 0;. } We can also call the string::data function on a std::​string object to get const char* . This approach will not work with C++98/03 standard. The first function foo should returns a single element arraylist, and the variable it returned has the same type as the type of the only element in the arraylist. The second function boo should returns a two-element arraylist but the type of returned variable has changed from .NET arraylist to normal powershell array.

C++ for Financial Mathematics, It will probably print some junk if you run it. However, you will then have to make sure the caller knows whether or not they will be expected to By convention in C and C++, if a function returns a pointer the caller is not expected to call delete[]. For example, if you call c_str() on a string you shouldn't delete[] what it returns. The C standard library provides numerous built-in functions that your program can call. For example, strcat () to concatenate two strings, memcpy () to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc. Defining a Function.

what is the best way to to convert c++ std::string to go string in cgo , call the c_str() method of std::string on that object before > It will work if it returns a reference or const reference, but is not guaranteed to work if  I do not have much experience with Turbo C++, but I do know that version 3.0 was released 2008 I believe. Borland now uses one called C++ Builder XE. I don't want to cause you a hassle, but If it were me, I would switch to a new IDE and compiler.

  • c_str() returns the pointer to the underlying char array. The problem is you're calling it on a temporary. So after the ; the object gets deleted, and presto: you get garbage.
  • Some information on "how" it's not working would help.. Compiler errors? Garbage data? lots of potential things wrong in just this snippet.
  • @Yeraze OP clearly stated it stores a garbage value, so it's definitely not a compiler error.
  • Either way, SomeFunction().c_str() will give you an invalid address. If you try to strcpy it, that will lead to undefined behavior.
  • Nope. Did it today. Worked great.
  • Could you provide a small, but complete working example that demonstrates this behavior?
  • That is different in a significant way. The problem is that c_str() is called on the result of a function call. This invalidates the internal char pointer that c_str() gives you because the string object, which is local to the function your calling, has gone out of scope. It also hasn't been copied as it would if you had something like string a = SomeFunction(); ... a.c_str();. This doesn't happen in the code linked to because c_str() isn't directly called on the result of a function call.
  • I feel that you didn't make that very clear. An example would really go a long way. In fact, I'm still not fully sure if you mean something like char* str = new char[...length goes here...]; strcpy(str, SomeFunction().c_str());.