Thread: Pointer dangling or not

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    113

    Pointer dangling or not

    This is an excerpt from an e-book
    Code:
    char *someFun()
    		{
    		char *temp = “string constant";
    		return temp;
    		}
    		int main()
    		{
    		puts(someFun());
    		}
    Code:
    Answer:
    		string constant 
    Explanation:
    		The program suffers no problem and gives the output 
    correctly because the character constants are stored in code/data area and not 
    allocated in stack, so this doesn’t lead to dangling pointers.
    Is it correct?? Are other pointers also stored in data area.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Seems good to me.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Your explanation is the details that apply with some implementations. The more correct justification is in the C++ standard, section 2.13.4, paragraph 1, which starts with;

    "A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n const char” and static storage duration (3.7), where n is the size of the string as defined below, and is initialized with the given characters. ...."

    In the above I've highlight the relevant bits: string literals are stored statically.

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Quote Originally Posted by grumpy
    "A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n const char” and static storage duration (3.7), where n is the size of the string as defined below, and is initialized with the given characters. ...."
    I took the liberty of highlighting something different. You should never assign a string literal to a non-const pointer, even though most compilers (and perhaps even the standard, can't remember) allow it for C compatibility.

    Thus it should be:
    Code:
    const char *someFun()
    {
    	const char *temp = "string constant";
    	return temp;
    }
    int main()
    {
    	std::cout << someFun() << "\n";
    }
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Quote Originally Posted by CornedBee
    I took the liberty of highlighting something different. You should never assign a string literal to a non-const pointer, even though most compilers (and perhaps even the standard, can't remember) allow it for C compatibility.

    Thus it should be:
    Code:
    const char *someFun()
    {
        const char *temp = "string constant";
        return temp;
    }
    int main()
    {
        std::cout << someFun() << "\n";
    }
    Hmm... Not sure if I'm following you here, CornedBee.

    You may not want temp to be a const expression. You certainly may want to have a string initialized from a string literal.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    It's a const char *, so it merely points to the constant string literal in memory. You'd want it to be const, because as mentioned, string literals are constant. You can't modify them.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Yes... I understand const T*.

    However, that is a far shot from saying "You should never assign a string literal to a non-const pointer, even though most compilers (and perhaps even the standard, can't remember) allow it for C compatibility.". That's what is confusing me.

    There's an implicit cast there, I agree. The constness of the string literal gets droped. But how else do you expect to initialize non const c-style strings?
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You shouldn't be able to.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    I'm sorry... but I must insist because either i'm being thick here or you are not putting much effort into your reply.

    "You shouldn't be able to" ?

    The standard also designates the term literal as const.
    Quote Originally Posted by page15 footnote
    The term “literal” generally designates, in this International Standard, those tokens that are called “constants” in ISO C.
    So what to say of int value = 15; ?
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    > int value = 15;
    You've requested this memory for your use. String literals are not meant to be changed ever because they are stored in memory that is not meant to be overwritten, merely accessed. This is to protect you from wantonly changing the return values of some functions.

    This chrashes as it should.
    Code:
    #include <iostream>
    using namespace std;
    
    char *f()
    {
      return "hello";
    }
    
    int main()
    {
      char *ptr = f();
      *ptr = 'j';
      cout << ptr << "\n";
      return 0;
    }
    The sane way is to allocate memory for your string literal so that you can change it.
    Code:
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    const char *f()
    {
      return "hello";
    }
    
    int main()
    {
      char arr[6];
      strcpy(arr, f());
      *arr = 'j';
      cout << arr << "\n";
      return 0;
    }

  11. #11
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by Mario F.
    So what to say of int value = 15; ?
    Apple; orange. The 15 is the item of interest in the comparison.

    [edit]I think I'm beginning to get where you are going, but could you please post an example of the string variety since it is highly germane to the discussion.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  12. #12
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    The value 15 itself is constant. This doesn't work:
    Code:
    15 = 7;
    Likewise, strings are constant. This shouldn't work:
    Code:
    strcpy("hippo", "potamus");
    But, as mentioned, some C compilers allowed it.

    You can change the value of a variable that has been assigned the value of an integral literal. You can't change the contents of a literal string. Changing the contents of a string is like doing this:
    Code:
    int *p = &7;
    *p = 5;
    You'd change the very meaning of 7 itself within your program!

    [edit] That post took a while for me to compile. Two people beat me to it. [/edit]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  13. #13
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    I'm not discussing string literals per-se. A string literal has the form const char*. That was established here, is established in the standards, and I know it. But that is not my point.

    My point is stating that you should not assign a string literal to anything other than a const char*.

    I don't think this is a correct statement. Or maybe a better way to put it, is incomplete.

    What I believe should have been said was something along the lines of "you can assign a string literal to a char* as a shorthand to having to do something like:
    char* temp = {'H','e','l','l','o',' ','W','o','r','l','d'}"

    Because the standard allows char* identifier = string_literal
    Last edited by Mario F.; 08-05-2006 at 05:50 PM.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  14. #14
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by Mario F.
    What I believe should have been said was something along the lines of "you can assign a string literal to a char* as a shorthand to having to do something like:
    char* temp = {'H','e','l','l','o',' ','W','o','r','l','d'}"

    Because the standard allows char* identifier = string_literal
    Hm. First, that's not quite a C-string. If it was, this is exactly the case for const -- you cannot modify what it's pointing to, so the pointer should reflect this. (I thought you may be going in the direction of arrays for a moment.) [edit]Or maybe you still are?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  15. #15
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Well, but those situations are no different than those created by a int* or, actually T*

    Maybe you guys are right. Maybe i'm totally missing the point. I credit you guys much more knowledgeable than me in C++, for I to be able to keep up with this argument for much longer in a clear conscience

    Quote Originally Posted by ISO-IEC 14882-2003 (4.2) discussing Standard (implicit) conversions
    A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type “pointer to
    char”;
    a wide string literal can be converted to an rvalue of type “pointer to wchar_t”. In either case,
    the result is a pointer to the first element of the array. This conversion is considered only when there is an
    explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an
    rvalue. [Note: this conversion is deprecated. See Annex D. ] For the purpose of ranking in overload resolution
    (13.3.3.1.1), this conversion is considered an array-to-pointer conversion followed by a qualification
    conversion (4.4). [Example: "abc" is converted to “pointer to const char” as an array-to-pointer conversion,
    and then to “pointer to char” as a qualification conversion
    . ]
    I'm sure you guys know this. And as such a string literal can be assigned to a char*. But maybe i'm missing the point as to what the original CornedBee intention was.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  2. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  3. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  4. How did you master pointers?
    By Afrinux in forum C Programming
    Replies: 15
    Last Post: 01-17-2006, 08:23 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM