CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Oct 2008
    Posts
    45

    string scope problem

    Code:
    	char *t2;
    	{
    		string t1="hello";
    		t2=(char*)t1.c_str();
    		cerr<<t2<<"\n";
    	}
    	cerr<<t2<<"\n";
    the first cerr is printing hello but the second one is printing nothing, it seems that when string t1 is going out of scope and deleting t2 is affected so it looks like when we do t2=(char*)t1.c_str(); t1.c_str() is returning just a pointer to the stiring in it not a pointer to another copy so when it gets destroyed t2 is pointing to nothing :S

    1- is what I saidtrue
    2- why does this happen, it seems so counter intuitive (why would they do it as so?)
    3- how can I get over that? (I need to return t2 afterwards)
    4- why didn't I get an error or garbage output when I printed t2 the second time I mean no body put t2=NULL so its still pointing to garbage :S

    thanks in advance

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: string scope problem

    The answers to your questions depend on what the type of t2 is. If it's a char*, then there will be a problem. If it's a std::string, there should not.

  3. #3
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: string scope problem

    Quote Originally Posted by Lindley View Post
    The answers to your questions depend on what the type of t2 is. If it's a char*, then there will be a problem. If it's a std::string, there should not.
    And since the posted code DOES show t2 to be a "char *", Lindley is correct in identifying this as an attempt to access memory which is no longer reserver by the string (which has gone out of scope), and thus induces undefined behviour...ANYTHING could happen!!!!!
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  4. #4
    Join Date
    Aug 2007
    Posts
    858

    Re: string scope problem

    so it looks like when we do t2=(char*)t1.c_str(); t1.c_str() is returning just a pointer to the stiring in it not a pointer to another copy
    That's exactly what it does. The data pointed to by c_str() is only guaranteed to be valid until the next non-const string member function is called.

  5. #5
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: string scope problem

    Quote Originally Posted by Speedo View Post
    That's exactly what it does. The data pointed to by c_str() is only guaranteed to be valid until the next non-const string member function is called.
    and the destructor is DEFINATELY a non-const member!
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  6. #6
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: string scope problem

    The data pointed to by c_str() is only guaranteed to be valid until the next non-const string member function is called
    What you mean here ?

    Code:
    string s1 = "Hello";
    const string s2 = "My name";
    string result = s1 + s2;
    
    char* t1 = result.c_str();
    
    // Display Hello only
    Is this what speedo mean ?

    Thanks.
    Thanks for your help.

  7. #7
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: string scope problem

    Quote Originally Posted by Peter_APIIT View Post
    What you mean here ?
    Code:
    char* t1 = result.c_str();
    // ANY call to a non-const method on result will make the value pointed to by  t1  undefined...
    WEhat part of that do you NOT understand???
    Last edited by TheCPUWizard; December 20th, 2008 at 11:37 PM. Reason: tagging
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  8. #8
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: string scope problem

    I think i understand that.

    It means that when result calls non const method(ANY), it will result undefined to char* t1;

    Thanks for your help.
    I didn't know this before.
    I really appreciated your help.
    Thanks for your help.

  9. #9
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: string scope problem

    Quote Originally Posted by Peter_APIIT View Post
    I didn't know this before.
    Then ONCE AGAIN...I suggest you spend some time studing the standard before continuing to program in C++ or make posts. The documentation is QUITE clear.

    21.3.6 basic_string string operations [lib.string.ops]

    const charT* c_str() const;

    Returns:
    A pointer to the initial element of an array of length size() + 1
    whose first size() elements equal the corresponding elements of the
    string controlled by *this and whose last element is a null charac-
    ter specified by traits::eos().

    Requires:
    The program shall not alter any of the values stored in the array.
    Nor shall the program treat the returned value as a valid pointer
    value after any subsequent call to a non-const member function of
    the class basic_string that designates the same object as this
    .
    Notes:
    Uses traits::eos().
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  10. #10
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: string scope problem

    I will take your advise seriously.
    Thanks.
    Last edited by Peter_APIIT; December 21st, 2008 at 03:11 AM.
    Thanks for your help.

  11. #11
    Join Date
    Oct 2008
    Posts
    45

    Re: string scope problem

    if any one is still wondering:
    1-It seems so from the discussion
    2-this is how it is in the standard
    3-simple use strcpy (duh)
    4-still don't know getting the same thing every time I print not garbage and no error after large numbers of runs, but who cares , don't do this and you'll be fine

    thanks guys

  12. #12
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: string scope problem

    Quote Originally Posted by compuKidd View Post
    4-still don't know getting the same thing every time I print not garbage and no error after large numbers of runs, but who cares , don't do this and you'll be fine

    thanks guys
    1) Go get an Egg (Chicken, or other animal)
    2) Securely (so it does not roll), pleace it in the middle of a heavily trafficed lane on a road.
    3) 99% of the vehicles will have their wheels near the boundaries of the lane (assuming the vehicle is driving centered on the lane).

    Your egg may survive for quite some time, but are you willing to place a monetary bet on how long??

    Thisd is the point of undefined behaviour. It may work for years. It may even be verifiably correct given a certain compiler/library/configuration; but may radically change at any time.

    You simply do not know what willl happen [replace egg in previous example with detonator for a large explosive device...it could get crusshed and destroyed or it could be triggered]
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  13. #13
    Join Date
    Aug 2005
    Location
    San Diego, CA
    Posts
    1,054

    Exclamation Re: string scope problem

    Quote Originally Posted by compuKidd View Post

    1- is what I saidtrue
    2- why does this happen, it seems so counter intuitive (why would they do it as so?)
    3- how can I get over that? (I need to return t2 afterwards)
    4- why didn't I get an error or garbage output when I printed t2 the second time I mean no body put t2=NULL so its still pointing to garbage :S

    thanks in advance
    2. Seems perfectly reasonable to me. What is counter intuitive about it? You made a pointer that points to something temporarily. Later that "something" was destroyed. It doesn't exist anymore yet for some reason you expect the pointer to continue to be valid. Your expectation is really the problem.
    3. Change t2 to be std::string and copy the string. You don't want to return a pointer to the char* anyway because the memory will be destroyed before the function returns (or in this case specifically, when the code block ends).
    4. Probably because std::string has a correctly implemented destructor which cleans up the memory. Once the std::string is deleted that memory is returned to the system. I'm not sure what the destructor does but perhaps it set itself to a NULL string.

    By the way, the std::string::c_str() method returns a const char*. Casting to a char* is not a good idea at all. The std::string object contains information about the character string. If you cast to a char* and try to modify the data the std::string object would be all messed up and would no longer function correctly. This is one reason why C++ programmers should not use c-style casting. c style casting is very powerful but allows you to do very naughty things like this, which will only cause trouble. Nothing good can come from this particular kind of casting operation!
    Last edited by kempofighter; December 22nd, 2008 at 02:09 PM. Reason: correction

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured