issue with code

Oct 6, 2022 at 2:35pm
Can anyone tell me the issue with below code? will it be segmentation fault?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

        #include <stdio.h>

        int main()

        {

            char *str = "hello, world\n";

            str[5] = '.';

            printf("%s\n", str);

            return 0;

        }
Oct 6, 2022 at 3:17pm
Perhaps C isn't as strict as C++ here, but line 8 should be a const char*, not char*, since you're pointing to read-only memory.

You are not allowed to modify the memory of a string literal (line 10), so this is likely what is causing a segfault.

Copy it into an array, first.
char str[] = "hello, world\n";
Last edited on Oct 6, 2022 at 3:19pm
Oct 6, 2022 at 3:23pm
The type of str is const char* (pointer to const char) and not char*. Hence you shouldn't try to change the data at L10. This would produce a compile error as C++.
Topic archived. No new replies allowed.