returning a pointer to stack variable

This is a discussion on returning a pointer to stack variable within the C++ Programming forums, part of the General Programming Boards category; Hi, while I know that returning pointers to stack/local/automatic variables is wrong: Code: int *f() { int i = 7; ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    6

    Question returning a pointer to stack variable

    Hi,
    while I know that returning pointers to stack/local/automatic variables is wrong:
    Code:
    int *f()
    {
      int i = 7;
      return &i;
    }
    I'm not sure how correct is this:
    Code:
    const char *f()
    {
      string s("whatever");
      return s.c_str();
    }
    the "s" var should be destroyed after the function returns, right? But what happens to the memory pointed to by the pointer returned by c_str()? Do I have to free/delete the memory pointed to by the pointer returned by c_str()?

    10x

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,775
    It is the same problem as the first example: s has been destroyed, so what you get from s.c_str() no longer exists, at least conceptually. You have no control over the string that you access via c_str(), so trying to use free() or delete[] on that invalid pointer would be wrong too.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    6
    10x for your answer

    then why the return type of c_str() is const char * ?
    and what is the right way to take in such situations?
    for example if I don't have control over the caller function

    so if I dynamically create a string object (string *s = new string("hello")) and if I free the memory pointed to by the pointer returned by s->c_str() do I also have to free/delete "s"?

    10x

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,775
    Quote Originally Posted by justAlamer
    then why the return type of c_str() is const char * ?
    Because you are not supposed to modify that string.

    Quote Originally Posted by justAlamer
    and what is the right way to take in such situations?
    for example if I don't have control over the caller function
    If you want to keep the return type as a pointer, you may have little choice but to write:
    Code:
    const char* f()
    {
        string s("whatever");
    
        // ...
    
        char* ret = new char[s.size() + 1];
        std::strcpy(ret, s.c_str());
        return ret;
    }
    On the other hand, there is also the option of:
    Code:
    std::string f()
    {
        std::string s("whatever");
    
        // ...
    
        return s;
    }
    or the use of an in/out parameter:
    Code:
    void f(std::string& s)
    {
        s = "whatever";
    
        // ...
    }
    Quote Originally Posted by justAlamer
    so if I dynamically create a string object (string *s = new string("hello")) and if I free the memory pointed to by the pointer returned by s->c_str() do I also have to free/delete "s"?
    You are not allowed to directly free the memory pointed to by the pointer returned by s->c_str(). What you can do in such a case is to delete s, or a copy of s... but why bother with manual memory management when you don't have to?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    6
    Thank you very much!
    I get it now.
    I don't wanna bother with manual memory management I just want to understand how it works and what is the right way to do it.

    thanks again

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,775
    You're welcome

    By the way, to emphasize how little control you have over the null terminated C-style string you can access by calling c_str(), consider:
    Code:
    std::string s = "hello world";
    const char* p = s.c_str();
    s.push_back('!');
    // p is no longer valid
    This does not just apply to push_back(), but to any non-const member function called on the corresponding std::string object.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Mar 2010
    Posts
    6
    That's wicked
    btw c_str() does not allocate additional memory, right?

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,775
    Quote Originally Posted by justAlamer
    btw c_str() does not allocate additional memory, right?
    It might; it depends on the implementation.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Mar 2010
    Posts
    6
    So do I have to care about freeing it?

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,775
    Quote Originally Posted by justAlamer
    So do I have to care about freeing it?
    No, you don't, no more than you have to care about freeing the other memory in use by the std::string object that will be destroyed when it goes out of scope.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Mar 2010
    Posts
    6
    Thanks a lot!
    You've been extremely helpful!

    cheers!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. infix evaluation using stack
    By lewissi in forum C++ Programming
    Replies: 0
    Last Post: 11-03-2005, 01:56 AM
  2. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Question about a stack using array of pointers
    By Ricochet in forum C++ Programming
    Replies: 6
    Last Post: 11-17-2003, 09:12 PM
  5. What am I doing wrong, stack?
    By TeenyTig in forum C Programming
    Replies: 2
    Last Post: 05-27-2002, 02:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21