resizing a string object

Hi -

I'm constructing a string object by an initial assignment and a large number of concatenations (using the += operator). After the string gets to a certain size (not very big; about 350 bytes), a concatenation fails. My string ultimately needs to be several thousand bytes long.

I assumed that the string would automatically resize itself; is this incorrect?

Thanks.
If you are using std::string (from the <string> library), then yes, the += operator will automatically allocate more space as needed.

The problem might be elsewhere. Can you post code?
Hi, Disch -

Yes, I'm using std::string. I think the problem may be in the compiler (it's for an ARM processor, and may have an arbitrarily small limit pre-set for string lengths). I'll check with the vendor now that I know my assumption was good.

Here's a code fragment that should give you the idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void telnetServer_main() {
    string  buffer;
    static	int		rc = 0; 				// error code
    int     nbrTokens;      // number of tokens successfully read from sscanf
    char    cmd[10];        // "GET" or "SET"
    char    cmdObject[10];	// pointer to the object (eg, "MOD" or "BYP")
    char    cmdValue[10];   // pointer to the value (eg, "ON" or "OFF")
    static	int32_t	iVal[NBR_PTS], qVal[NBR_PTS];
    char	str[80];

    nbrTokens = sscanf(buffer.c_str(), "%s %s %s", cmd, cmdObject, cmdValue);

    getPts(iVal, qVal);
    buffer = "PTS: ";
    buffer += LINE_BRK;
    for (int i = 0; i < NBR_PTS; ++i)
    {
        sprintf(str, "%d %d %d ", i, iVal[i], qVal[i]);
        buffer += str;
        buffer += LINE_BRK;
    }
    return rc;
}
Don't contact the vendor. The problem is in your code.

sscanf(buffer.c_str(),

c_str gives you a read only buffer to the string. By writing to it you are very likely stepping out of bounds of the string and corrupting memory. you must never ever ever do this.

I'm surprised this even compiled, as sscanf takes a char* and c_str clearly returns a const char*. It should have errored on you.


General rule: do not mix C string functions with C++ strings.


EDIT:

I got sscanf and sprintf mixed up. Disregard.
Last edited on
I appreciate the feedback anyway; it's a good reminder.

Apart from the fact that this "should" work, is it still considered poor form to use the c_str() as I have here?
Topic archived. No new replies allowed.