3

I wrote a function in C that transforms all lowercase letters into uppercase with pointers. It looks like the following:

char    *ft_strupcase(char *str)
{
    char    *str_begin;

    str_begin = str;
    while (*str != '\0')
    {
        if (*str >= 'a' && *str <= 'z')
        {
            *str = *str - 32;
        }
        str++;
    }
    return (str_begin);
}

However, if I test with the following main function, it will give a bus error:

#include "ft_strupcase.c"

int main(void)
{
    printf("The string \"I am your father\" is now %s\n", ft_strupcase("I am your father"));
    return (0);
}

The error message looks like the following:

/bin/sh: line 1: 79346 Bus error: 10

But if I create a string variable to store the string, there is no bus error. For example, if I test it with the following main function:

#include "ft_strupcase.c"

int main(void)
{
    char test_string[50] = "I am your father";

    printf("The string \"I am your father\" is now %s\n", ft_strupcase(test_string));
    return (0);
}

It works fine, and the output is:

The string "I am your father" is now I AM YOUR FATHER

I don't really understand how the first test differs from the second test. Can anyone explain to me why this happens?

Robb U
  • 31
  • 1
  • 1
    In the first test, your string literal is stored in read only memory hence you are getting an error when you try to modify it. In the second test, you copy the string literal into an array then modify so it works. – Emmanuel Mathi-Amorim Feb 14 '20 at 02:44
  • 1
    Does this answer your question? [Why Can I not modify a string literal in c?](https://stackoverflow.com/questions/58584310/why-can-i-not-modify-a-string-literal-in-c) – Emmanuel Mathi-Amorim Feb 14 '20 at 02:46

1 Answers1

5

The C standard states that string literals are read only. In many cases, they are actually stored in a read-only section of memory.

When you attempt to modify a string literal, you invoke undefined behavior, which in this case causes the program to crash.

In contrast, the array you pass in the second example is writable, so the program runs successfully.

dbush
  • 205,898
  • 23
  • 218
  • 273