0

Why I am getting like this when i run my code

~/workspace/ $ make initials
clang -fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wshadow    initials.c  -lcrypt -lcs50 -lm -o initials
~/workspace/ $ ./initials
david
DSegmentation fault
~/workspace/ $ 

my code is

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

int main(void)
{
    // takes input from user as their name
    string name = get_string();
    int length = 0;
    // checking up to the end of the progam
    while (length != strlen(name) )
    {
        // checking for the spaces before first ch
        while (name[length] == 32)
        {
            length++;
        }
        printf("%c",toupper(name[length]));
        while (name[length] != 32)
        {
            length++;
        }
        printf("%c",toupper(name[length]));
    }
}
0

When you write length!=strlen (name) even after length exceeds your strings length..the first condition would be true. So when name[length] .where length would be greater than your strings length.. Which gives you a segmentation fault. To check the value of length , use debug50 to understand your code. If this help please vote. Have a great time coding :)

| improve this answer | |
1

Your inner loops don't explicitly respect the string length, the first one does it implicitly (string end is not a space). You could add some name[length]!='\0' && or length < strlen(name) && in front of the second inner loop's condition, and remove the second printf (it's either a space or the string end, you don't want to print any of those).

Also make sure to print a newline after your loop.

It feels like a good idea to have the outer loop use < rather than !=, so that if you for any reason happen to have your value >, you'd immediately stop looping.

As strlen(name) won't change its value, but is frequently used, consider saving it to its own variable, and using that one instead.

| improve this answer | |

You must log in to answer this question.

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