1

I'm learning C and I got a task to to remove the lowercase vowels (a, e, i, o, u) in a given string. so I wrote this code and I'm getting Segmentation fault error in line 15, can someone explain me why I'm getting this error, how to avoid getting this error, and how to solve this error?

Thx, appreciated!

#include <stdio.h>

char *shortcut(char *str_out, const char *str_in);

int main()
{
    shortcut("", "how are you today?");
    return 0;
}

char *shortcut (char *str_out, const char *str_in)
{
    for (int i = 0; str_in[i] != 0; i++) {
        if (str_in[i] != 'a' && str_in[i] != 'e' && str_in[i] != 'i' && str_in[i] != 'o' && str_in[i] != 'u')
            *str_out++ = str_in[i];
    }

    *str_out = '\0'; // write to str_out
    return str_out; // return it
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Patton13
  • 27
  • 5
  • 2
    Modifying string literals is undefined behavior. Look at your first parameters. – PaulMcKenzie Jan 15 '22 at 23:11
  • Use a modifiable array of characters, i.e. `char something[100]; shortcut(something, "abc123");` – PaulMcKenzie Jan 15 '22 at 23:16
  • why are comparing against 0 in your for loop? – Ait-Gacem Nabil Jan 15 '22 at 23:16
  • @PaulMcKenzie This is the task "Create a function called shortcut to remove the lowercase vowels (a, e, i, o, u ) in a given string." this is the given code to start ```char *shortcut (char *str_out, const char *str_in) { *str_out = '\0'; // write to str_out return str_out; // return it }``` – Patton13 Jan 15 '22 at 23:17
  • 1
    @Ait-GacemNabil instead of calculating the elements in the array I just used it... – Patton13 Jan 15 '22 at 23:19
  • @Patton13 So what's wrong with using the array I mentioned already? Have you tried it yet? Bottom line is that you cannot modify string literals, no matter what "task" was given you. – PaulMcKenzie Jan 15 '22 at 23:20
  • @PaulMcKenzie Yea I tried it, I don't get the error now but it fails on the task... – Patton13 Jan 15 '22 at 23:24
  • Even if you *could* modify the string literal, `""` doesn't have room to be written to. – Weather Vane Jan 15 '22 at 23:30
  • The program doesn't output anything... – Weather Vane Jan 15 '22 at 23:34
  • Not just because you don't print anything, but because `return str_out` points to "the empty string". Presumably you are using, following @PaulMcKenzie, `printf("%s\n", shortcut(something, "how are you today?"));` You need to return the *original value* of the pointer. – Weather Vane Jan 15 '22 at 23:49
  • Understood thanks you all! – Patton13 Jan 15 '22 at 23:58

0 Answers0