0

When I run this program, I get the message "segmentation fault (core dumped)." Any help with fixing this would be appreciated.

    //Initials Generator//
    //Grabs name from user and prints initials to screen//

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

    int main(void)
    {
         printf("Name please:");
         string s = GetString();

         int i = 0;
         int nameleng = strlen(s);

        do
        {
            if (s[i] < 97)
            {
                printf("%c" , s[i]);
            }
            else
            {
                int new = s[i] - 32;
                printf("%c" , (char) new);
            }

           while (s[i] != ' ')
           {
                i++;
           }

           i++;

        }    
        while (i < nameleng);

     printf("\n");
     return 0;

}

1

Look at the following:

       while (s[i] != ' ')
       {
            i++;
       }

If there are no spaces in the reaminder of the string when this is encountered, it will just keep incrementing i forever. You are guaranteed to go beyond the end of the s string, resulting in a seg fault. You need to rethink the logic behind this.

If this answers your question, please click on the check mark to accept the answer. Let's keep up on forum maintenance. ;-)

1
  • Thanks for your help! I changed the condition, and the program runs correctly now. Nov 25 '15 at 22:40

You must log in to answer this question.

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