string.assign -- SEGFAULT problems

This is a discussion on string.assign -- SEGFAULT problems within the C++ Programming forums, part of the General Programming Boards category; compiles fine using gcc - segfaults here: Code: while ( lower <= length ) { upper = s1.find( s2, lower ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    3

    string.assign -- SEGFAULT problems

    compiles fine using gcc - segfaults here:

    Code:
    while ( lower <= length ) {
            upper = s1.find( s2, lower );                  // location of space
            word.assign( s1, lower, (upper - lower) );     // SEG HERE!!!
            array[counter] = word;                         // take value from word and assign to array
            counter++;                                     // increase counter used to step thru array space
            lower = upper + 1;                             // for next iteration, start one char to the right of our last 'upper' bound
    }
    just a little program to pull out words from a longer string (words being strings of characters between whitespace).

    s1 = "my dog has fleas but my cat don't"
    s2 = " "
    word = ""

    length = s1.length()

    initial value of lower is 0 -- both lower & upper are ints.

    I guess I must be using assign wrong, but can't seem to figure out how.
    Last edited by nateDC; 01-20-2005 at 12:13 PM.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    We can't do anything unless you post the whole program, and the example data which makes it crash.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    3
    Sorry, new here, and just thought I'd best follow forum guidelines 'till I knew better.

    11. When posting code please do not post your entire program if you only need help with one function. Post as little as possible. People are much more likely to read small amounts of code and help you than they are to read a hundred lines of code.
    At any rate, the *entire* program is below, but I don't really think the rest of the code is relevant -- I'm happy to be wrong though. And all the pertinent values for that loop are listed right below it, with the exception of 'counter', which I should have said was initialized to zero.

    Here's the entire thing, if it helps:
    Code:
    #include <iostream>
    #include <string>
    
    using std::string;
    using std::cout;
    using std::endl;
    
    int main() {
    
        // variable creating ***************************************
        // upper will end up holding the location of the space
        // lower will end up holding the beginning of current word
        // ( so with these two vars we have a beginning and end position
        // for each word in the longer string
        //
        // counter is used to step through array
        //
        int upper, lower = 0, counter = 0;
    
        // s1 is our string
        // s2 is our test string (we're testing for spaces)
        // word will hold the word we pull out from s1 before
        // assigning it to our string array
        //
        string s1 = "My dog has fleas but my cat don't";
        string s2 = " ";
        string word = "";
    
        // our string array is big enough for the words in s1
        // initially initialized with "nothing" values for each
        // array sub-value
        //
        string array[8];
        for ( int n = 0; n < 8; n++ )
            array[n] = "nothing";
    
        // print out the initialized array
        //
        for ( int a = 0; a < 8; a++ )
            cout << a << " " << array[a] << endl;
    
        // assign length of s1 to length so we don't recalulate it
        // each time through the loop -- probably the compiler is
        // smart enough to optimise this for use, but better safe
        // than sorry
        //
        int length = s1.length();
        cout << endl << length << endl << endl;
    
        // loop continues until value of lower becomes greater than
        // the length of the string s1
        //
        while ( lower <= length ) {
            upper = s1.find( s2, lower ); // location of space
            word.assign( s1, lower, (upper - lower) ); // SEG HERE!!!
            array[counter] = word; // take value from word and assign to array
            counter++; // increase counter used to step thru array space
            lower = upper + 1; // for next iteration, start one char to the right
                               // of our last 'upper' bound
        }
    
        cout << s1 << endl << endl; // print out entire value of s1
    
        // step through array once more and print out values - should be
        // the individual words we've pulled from s1 (words defined by
        // characters delimited by whitespace)
        //
        for( int q = 0; q < 8; q++ ) {
            cout << array[q] << endl;
        }
    
        return 0;
    
    }

  4. #4
    C Programmer Stack Overflow's Avatar
    Join Date
    Apr 2004
    Posts
    477
    Hello,

    I added this line of code:
    Code:
    cout << "upper: " << upper << " | lower: " << lower << endl;
    Before this line:
    Code:
    word.assign( s1, lower, (upper - lower) ); // SEG HERE!!!
    And this is what it printed:
    Code:
    upper: 2 | lower: 0
    upper: 6 | lower: 3
    upper: 10 | lower: 7
    upper: 16 | lower: 11
    upper: 20 | lower: 17
    upper: 23 | lower: 21
    upper: 27 | lower: 24
    upper: -1 | lower: 28
    upper: 2 | lower: 0
    upper: -1 | lower: 3
    That may explain why the segmentation fault occurs.

    (upper - lower) : (-1 - 3) = -4


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  5. #5
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    I agree with Stack Overflow. I fixed this by initializing upper to 0 and changing the condition of the while loop to while(upper != string::npos);
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    3
    Ahhh... boundary checking. It's not *just* a nice idea, huh?

    Should've really thought to check that a bit more stringently on my own... sorry.

    But thank you for the help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 01-02-2009, 06:24 AM
  2. No clue how to make a code to solve problems!
    By ctnzn in forum C Programming
    Replies: 8
    Last Post: 10-16-2008, 02:59 AM
  3. malloc() resulting in a SegFault?!
    By cipher82 in forum C++ Programming
    Replies: 21
    Last Post: 09-18-2008, 11:24 AM
  4. use of printf prevents segfault!
    By MK27 in forum C Programming
    Replies: 31
    Last Post: 08-27-2008, 12:38 PM
  5. Segfault problems
    By Ichmael™ in forum C++ Programming
    Replies: 4
    Last Post: 09-12-2004, 12:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21