This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

cpp string buffer size

Other Parts Discussed in Thread: LM3S6965

Hi,

I am trying to initialize a cpp string. Whever the length if the string is less than 15 characters everything works fine but when I try and use a string of 16 or more characters the buffer doesn't change size and the 16 spaces are filled with garbage. Below some screenshots...

 

using:

string plot ("123456789012345");

 

 

using:

string plot ("1234567890123456789");

 

*Notice how _MySize is now 19 which is correct but the buffer is still 16

 

Any idea why this happen? I'm running this on an Stellaris LM3S6965

 

Thanks in advance for any help

  • The implementation of the std::string object has a small array data member named _Buf  in which it keeps short strings, but longer strings are stored in dynamically allocated memory.  For short strings you'll see the characters in _Buf, but longer strings are stored where _Ptr points.  In fact, your own screenshot shows that _Ptr is indeed pointing to a C string that has the right content (it isn't showing the rest of the string past the 10th character).

    You're not meant to look directly at the data members of C++ library objects.  What does CCS say for the value of plot.c_str() ?

  • The problem is I'm trying to use strings and send them to a thermal printer over UART. When I break down the string into characters to send them via uart it sends the garbage stored in _BUF... I have tried changing it to c_str and the same thing happens. If I run the exact same code with a short string it works fine... Right now I'm on my phone, as soon as I get to the computer where I have the source code I'll post it... I don't have a lot of experience in cpp so it may be a newbie mistake...

  • This function sends the garbage in _BUF if the string is longer than 15 chars...

     

    void Foo(const string& text) {

     int charCounter = 0;

     for(charCounter=0; charCounter < text.length(); charCounter++)

     {  

            UARTCharPut(UART1_BASE, (unsigned)text[charCounter]);  

    }

     NewLine();

    }

  • Got it working by sending the c_str to the function...

     

     

    string plot ("Transaction Tracker Report");

    plot.append(" 1234567890123456789");

    UARTSend((unsigned char *)plot.c_str(), plot.length());

     

     

    void UARTSend(const unsigned char *pucBuffer, unsigned long ulCount)

     {    

     //    

     // Loop while there are more characters to send.    

     //     while(ulCount--)    

     {        

             // Write the next character to the UART.        

             UARTCharPut(UART1_BASE, *pucBuffer++);    

     }

        NewLine();

    }