0

I, like so many others, have ran into the dreaded 'Segmentation fault' error. For the life of me, I just can't figure out where I'm going wrong here. I've tried slowly working through it on a notepad but I just can't identify a fault in the logic. Hopefully, one of you good people can help me. I was told elsewhere that I can't nestle 'while' loops. Is that the case?

Ideally, I'd like someone to explain why the error occurs in fairly simple terms and not just how to fix it.

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


int main(void)
{
    string name = get_string();
    int i = 0;
    int length = strlen(name);

    if (name != NULL)
    {
        while (i < length)
        {
            while (name[i] == ' ')
            {
                i++;
            }

            printf("%c", toupper(name[i]));       

            while (name[i] != ' ')
            {
                i++;
            }
        }        
    }
    printf("\n");
}

Having had a quick look through some of the similar code for the 'Initials' challenge, I've noticed that my approach is pretty unique. Have I gone about solving this problem in a really obscure/inefficient way?

Edit: I should probably point out that the code executes flawlessly. It's able to sift through the spaces and pick out the first character of each word in a string. It just also prints a 'segmentation fault' error.

0

There's a problem with your use of ' ', so consider the ASCII table.

I suggest you use a bool that fires off at the start of a new word. It would need to be set to true at the beginning, for the first letter, then turn off and fire at the start of the next word. Printing can occur when the bool is true.

You don't have return 0; in your code.

2
  • Thanks for the help. It wasn't necessary to use 'return 0;' or the Ascii values, but I did restructure the program to trigger with 'if' and 'else' conditions instead. Do you know why the 'Segmentation fault' was triggered? Apparently, it's a memory issue; but I can't see where I went wrong and I'd like to be able to diagnose it if it happens again.
    – Syates29
    Mar 12 '17 at 12:30
  • I had the same problem too! This answer from another user might be helpful. " 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." Jun 2 '17 at 11:48

You must log in to answer this question.

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