Why I can modify a char in the string with CLion?


#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *name = "Thank you";
    name[0] = 'a';
    printf("%s", name);

and it's works fine it works

but isn't that name[0] = 'a' should not work? Why it's working?

answered question

1 Answer


C standard imposes no restriction on attempting to modify a string literal. However, if you attempt to modify a string literal, the outcome is undefined behaviour.

Quoting C11, chapter 6.4.5 (String literals)/P7

[...] If the program attempts to modify such an array, the behavior is undefined.

The fact that you think the program is allowing you to modify the content of the string literal is one of the many outcome of the UB.

posted this

Have an answer?


Please login first before posting an answer.