Returning String Literals from a function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Siam

    Returning String Literals from a function

    Hi all...

    What's the best way to return some string from a function (without
    using the string class). Would the following work:

    char* getString( )
    {
    return "TheString" ;
    }

    I've seen this in code in a lot of places, but I would have thought the
    string literal in the function would be allocated on the stack, a
    pointer to the string will be returned, and the block of memory holding
    the string would be deallocated when the function returns... Would it
    make a difference if the return type was const char* ?

    If this doesn't work, the only other way I can think of is to either
    dynamically allocate a new string in the function (in which case it
    wouldn't be clear to the user to delete it), or to make them pass a
    reference to a string and strcpy "TheString" into it (which I find
    annoying)... Is there any other way?

  • tragomaskhalos

    #2
    Re: Returning String Literals from a function


    Siam wrote:
    Hi all...
    >
    What's the best way to return some string from a function (without
    using the string class). Would the following work:
    >
    char* getString( )
    {
    return "TheString" ;
    }
    >
    I've seen this in code in a lot of places, but I would have thought the
    string literal in the function would be allocated on the stack, a
    pointer to the string will be returned, and the block of memory holding
    the string would be deallocated when the function returns... Would it
    make a difference if the return type was const char* ?
    Don't worry, the code is fine. The string literal itself is stored
    globally, the function just returns a pointer to that global location.
    Returning const char* would be better though, as the returned string
    should not be modified by the caller.

    Comment

    • Frederick Gotham

      #3
      Re: Returning String Literals from a function

      Siam posted:
      Hi all...
      >
      What's the best way to return some string from a function (without
      using the string class). Would the following work:
      >
      char* getString( )
      {
      return "TheString" ;
      }

      Put a "const" in there:

      char const *GetStr()
      {
      return "Hello";
      }

      If it helps your understanding, you could think of the snippet above as
      being equivalent to:

      char const str[] = "Hello";

      char const *GetStr()
      {
      return str;
      }

      You can see that you're simply returning the address of a global object --
      so no memory is leaked, and no object is accessed after having being
      destroyed.

      --

      Frederick Gotham

      Comment

      • Siam

        #4
        Re: Returning String Literals from a function

        Cheers.. One more question.. Would the following code be alright?

        char* getString( )
        {
        string s = "TheString" ; //using string class
        return s.c_str();
        }

        Does c_str() create a global string literal and return its address, or
        is this one allocated on the stack?

        Cheers :)

        Siam

        Comment

        • Victor Bazarov

          #5
          Re: Returning String Literals from a function

          Siam wrote:
          Cheers.. One more question.. Would the following code be alright?
          >
          char* getString( )
          {
          string s = "TheString" ; //using string class
          return s.c_str();
          }
          No, most certainly not.
          Does c_str() create a global string literal and return its address, or
          is this one allocated on the stack?
          Unknown. It's magic. But in your case 's' is still a local object, and
          it's destroyed when the fucntion ends. Whatever 'c_str' returns is tied
          to that object, so the pointer you get is invalid as soon as the function
          returns.

          V
          --
          Please remove capital 'A's when replying by e-mail
          I do not respond to top-posted replies, please don't ask


          Comment

          • tragomaskhalos

            #6
            Re: Returning String Literals from a function


            Siam wrote:
            Cheers.. One more question.. Would the following code be alright?
            >
            char* getString( )
            {
            string s = "TheString" ; //using string class
            return s.c_str();
            }
            Does c_str() create a global string literal and return its address, or
            is this one allocated on the stack?
            No you can't do this. In your string class example above the global
            literal "TheString" gets copied into some memory managed by the
            std::string s , c_str() then returns a pointer to this memory
            (technically it might be a copy again, but let's ignore that
            complexity), but once you return from the function the std::string s
            goes out of scope, and the memory it manages is effectively lost. Hence
            any attempt to use the return from this function will likely blow up in
            your face.

            Comment

            • Frederick Gotham

              #7
              Re: Returning String Literals from a function

              Siam posted:
              char* getString( )

              Stop using "pointer to non-const" to store the address of a string literal --
              it's sloppy. The following code demonstrates:

              char *PoorlyWrittenF unction()
              {
              return "I'm a string literal, and am inherently const, "
              "even though the C type system doesn't acknowledge"
              "it.";
              }

              int main(void)
              {
              *PoorlyWrittenF unction() = 'e';
              }


              The above code compiles without error, but invokes undefined behaviour
              nonetheless.

              --

              Frederick Gotham

              Comment

              Working...