0

Getting a segmentation fault in line 21, never seen this before and don't know how to fix it. Anyone might point me in the right direction?

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
   //prompt user for name
   string s = get_string();
   if (s != NULL)
   {
        //first letter
        for(int i = 0, n = strlen(s); i < n; i++)
        {
            if (i < 1)
            {
                printf("%c", toupper(s[i]));
                i++;
            }
            // for letter after space?
            for (;s[i] != ' '; i++); //receiving seg fault in this line
            i++;
            printf("%c", toupper(s[i]));
        }
    }
    printf("\n");
}

2 Answers 2

1

The syntax is wrong in the second for loop on line 21. Instead of that second for loop, you probably want an if statement to check whether the current character at i is a space and if so, print the character at i+1. You can use the syntax s[i+1] to print the next character without advancing the loop. You do not need, certainly not in this case, to increase i within a for loop after the main definition.

0

The reason of segfault is the condition of the second for loop:

s[i] != ' '

Suppose we have a string with no spaces, the stop condition is never fulfilled so that we enter an infinite loop (the end condition of cycle i < n does not affect the second loop until it end ). The lesson is that we must be careful that loops actually end

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .