Problem with std::string erase function.

Discussion in 'C++' started by Tero Toivanen, Oct 14, 2004.

  1. Dear experts,

    I am doing code to Solaris 9 system with C++.

    I get every now and then segmentation fault in the following code that
    removes
    heading and trailing white spaces (mLineStr is of type std:string):

    ------

    1: void ClassXXX::FunctionYYY (const std::string & inCmd)
    2: {
    3: mLineStr = inCmd;
    4:
    5: int tmpSpaceNum = 0;
    6: int tmpLength = mLineStr.length();
    7:
    8: // remove heading white spaces
    9: for (int idx1=0; idx1 < tmpLength; idx1++)
    10: {
    11: if (isspace( mLineStr [idx1] ))
    12: {
    13: tmpSpaceNum++;
    14: }
    15: else
    16: break;
    17: }
    18:
    19: mLineStr.erase (0, tmpSpaceNum);
    20:
    21: tmpSpaceNum = 0;
    22: tmpLength = mLineStr.length();
    23:
    24: // remove trailing whites paces
    25: for (int idx2=tmpLength-1; idx2 >= 0; idx2--)
    26: {
    27: if (isspace( mLineStr [idx2] ))
    28: {
    29: tmpSpaceNum++;
    30: }
    31: else
    32: break; // leave the loop
    33:
    34: }
    35:
    36: mLineStr.erase (tmpLength-tmpSpaceNum, tmpSpaceNum);

    -------

    Now with mLineStr = "foobar -d jomppe -m4 " there will be segmentation
    fault
    in the last line with a printing to stderr: "Position 20 is greater than
    size 6" . This
    segmentation fault does not come every time, but only every now and
    then. I guess
    the segmentation fault comes because an exception is not catched, but I
    cannot
    understand the reason for the exception!

    Is the memory somehow corrupted or is there some known bugs in erase
    function?
    After all, in line 22 the length of mLineStr still seems to be 21
    characters, but in
    line 36 it is for some reason 6...

    Thank you very much in advance,

    Tero
    Tero Toivanen, Oct 14, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tero Toivanen
    Replies:
    0
    Views:
    404
    Tero Toivanen
    Oct 14, 2004
  2. Tero Toivanen
    Replies:
    1
    Views:
    3,321
    Chris \( Val \)
    Oct 14, 2004
  3. Tero Toivanen
    Replies:
    1
    Views:
    401
    John Harrison
    Oct 14, 2004
  4. erase vs. erase

    , Mar 25, 2006, in forum: C++
    Replies:
    7
    Views:
    351
    Pete Becker
    Mar 30, 2006
  5. Replies:
    3
    Views:
    324
    terminator
    Mar 25, 2007
Loading...

Share This Page