assigments to string pointers with literals

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jorba101
    New Member
    • Jun 2008
    • 86

    assigments to string pointers with literals

    I wonder if that is correct, in ANSI C:

    char *mystring;

    mystring = "helloworld ";

    or I should always proceed in this other, thougher, way:

    char *mystring;

    if( NULL == ( mystring = malloc( strlen( "helloworld ") ) ) )
    {
    printf("error\n ");
    }
    else
    {
    strcpy( mystring, "helloworld " );
    }

    Thanks!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by jorba101
    char *mystring;

    mystring = "helloworld ";
    Well strictly speaking a string literal is constant (or should be treated that way, it is not necessarily constant on all platforms) so this should be
    [code=c]
    const char *mystring;

    mystring = "helloworld ";
    [/code]
    to preserve the constness of the data but otherwise this is acceptable.

    Comment

    • jorba101
      New Member
      • Jun 2008
      • 86

      #3
      So,

      this means that:

      I can safely assume that the compiler will reserve memory in the heap for mystring, for this const value?

      Thanks.-

      Comment

      • jorba101
        New Member
        • Jun 2008
        • 86

        #4
        Going further,

        You mean that, it is only possible if mystring is const? (i.e. its value can't be changed runtime?)

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          I would generally proceed the tougher way. The reason is that passing pointers around a program ios one of the most dangerous things you can do especially when the compiler is in charge of deleting your data. By using malloc() and managing your own memory, you are responsible for deleting and this makes passing the pointer safer. Of course, you have to remember to delete and this brings its own set of problems.

          Also, using the stack can cause problems since stack memory if often limited. Exceed it and your program crashes.

          Comment

          • Banfa
            Recognized Expert Expert
            • Feb 2006
            • 9067

            #6
            Originally posted by jorba101
            I can safely assume that the compiler will reserve memory in the heap for mystring, for this const value?
            No, where the compiler reserves space for mystring is rather dependent on how and where you declare it but the 2 choices for the given declaration are on the stack, if the declaration is made inside a function or in global data (in the data segment) if you declare the variable outside the function but this would be poor technique.

            The compiler will reserve memory for the string constant in the programs data segment, possibly in a constant data segment depending on the platform.

            Comment

            • Banfa
              Recognized Expert Expert
              • Feb 2006
              • 9067

              #7
              Originally posted by jorba101
              You mean that, it is only possible if mystring is const? (i.e. its value can't be changed runtime?)
              No I mean if you want to change the value of mystring then you have to allocate memory from the heap for it.

              However if you have no intention of changing what mystring is pointing to then you can conserve memory by declaring it const and just pointing it to the string literal. This is commonly used to conserve both ram and prom on a platform with limited amounts of either or both (particularly if the only compiler available is non optimising) with a definition
              [code=c]
              const char * const mystring = "Hello World";
              [/code]
              Allows the use of mystring where every you need the constant string "Hello World".

              Comment

              • Banfa
                Recognized Expert Expert
                • Feb 2006
                • 9067

                #8
                Originally posted by weaknessforcats
                I would generally proceed the tougher way. The reason is that passing pointers around a program ios one of the most dangerous things you can do especially when the compiler is in charge of deleting your data. By using malloc() and managing your own memory, you are responsible for deleting and this makes passing the pointer safer. Of course, you have to remember to delete and this brings its own set of problems.

                Also, using the stack can cause problems since stack memory if often limited. Exceed it and your program crashes.
                Personally I disagree. In this limited example allocating from the heap does not reduce the use of the stack there is no data to delete, the string constant appears in the data segment and always will the pointer appears on the stack or in global data and always will. Pointers become (a little) safer when they are const, although it is true that many programmers skip on using the const keyword when they should.

                In most applications and certainly in an application on a platform with limited resources there is a lot to be said for the adage of "keep it simple" and this means not putting in unrequired memory allocations.

                Of course (as I said earlier) if the program is going to need to change the string then the string constant should be copied to ram first. Whether that is the on the stack or the heap rather depends on how the platform has its ram arranged (more available as stack or more available as heap) but the distinct advantage of using the heap is that you can programatically ensure that you have allocated enough ram to contain the string even if the string changes length in the future which you can not do with a string allocated on the stack.

                Comment

                • jorba101
                  New Member
                  • Jun 2008
                  • 86

                  #9
                  Ok then.

                  Btw,

                  const char * const mystring = "Hello World";
                  I can understand why that saves RAM. But still I can't see how this saves PROM. Why does it?

                  Thanks,

                  Comment

                  • Banfa
                    Recognized Expert Expert
                    • Feb 2006
                    • 9067

                    #10
                    Originally posted by jorba101
                    I can understand why that saves RAM. But still I can't see how this saves PROM. Why does it?
                    With some compilers (particularly non-optimising ones) if you do this
                    [code=c]
                    char string1[20];
                    char string2[20];

                    strcpy(string1, "Hello World");
                    strcpy(string2, "Hello World");
                    [/code]
                    then you end up with 2 copies of the string literal "Hello World" in the data segment, by using a const pointer
                    [code=c]
                    const char * const pHelloWorld = "Hello World";

                    char string1[20];
                    char string2[20];

                    strcpy(string1, pHelloWorld);
                    strcpy(string2, pHelloWorld);
                    [/code]
                    there is only 1 string literal and it only appears in the data segment once, you save the size of the string minus the size of a pointer in prom.

                    Now in this example this may not sound very significant, however I worked on an embedded project for a piece of equipment, the front panel (LCD and buttons) for the equipment was control from a separate micro processor board. The program on that board needed extending, however there was no program memory (FLASH in this case) space left. The main contractor declared that in order to extend the program we would have to re-spin the board hardware design to fit a larger flash chip.

                    However when we examined the code we noticed that the string literal "  &# 160; &#160 ;  &# 160; &#160 ;  &# 160; &#160 ;  &# 160; &#160 ;" appeared umpteen times. When that was replaced by a single string literal and a pointer it saved 20k bytes of program space allowing the development to continue without a costly hardware re-spin and the time delay that would have caused.

                    In case you are wondering it was used very where the LCD needed clearing which suggests to me poorly structured code as I imagine a single function to clear the LCD would have avoided the problem in the first place.

                    Comment

                    Working...