char *p = "hello"; p[0] = 'H'; is executed. What is the status of this program under the C standard?
Correct answer
A. Undefined behaviour, because the string literal has static storage and must not be modified
16 views
A. Undefined behaviour, because the string literal has static storage and must not be modified
16 views
String literals live in static storage and modifying them is undefined behaviour, so many toolchains place them in read-only pages and the write faults. The pointer is non-const, which is why the compiler cannot stop you, and that makes the idiom dangerous. Copying into an array, char s[] = "hello"; s[0] = 'H';, is well defined because the array holds a modifiable copy.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is A? Ask here and get an explanation.