Segmentation Fault C++

workspace

#1

Hey guys,

Sorry if this is a noob question, but I have not been able to find any information anywhere regarding this issue and thought it’d be best just to reach out to the community for answer.

I’ve got a basic c++ project I’m working on for my CS class and I keep getting this error when I run my file:

bash: line 12: 5784 Segmentation fault $file.o $args

Here is my code:

int str_len(char s[], int start);

int main() {

    char sentence[81];
    cout << "Enter a sentence: \n";
    cin.getline(sentence, 81);
    cout << "There are " << str_len(sentence, 0) << " characters in the sentence." << endl;
    
    return 0;
}

int str_len(char s[], int start) {
    if(s[start] == '\0')
        return 0;
    return 1 + str_len(s, start);
    
    return 0;
}

// it seems that my function str_len is the one causing the segmentation fault. When I comment that out it runs fine. Is this a bug in my code or a bug with Cloud9? I haven’t had a chance to test this code on a non-cloud based IDE.

Any help is appreciated!


#2

I actually figured it out. I had to add a ‘+1’ to

return 1 + str_len(s, start+1);