What happens when a C program executes char *s = "hello"; s[0] = 'H';?
Correct answer
A. Undefined behaviour, because the literal is read-only
13 views
A. Undefined behaviour, because the literal is read-only
13 views
The assignment makes s point at a string literal, which typically lives in a read-only segment of the executable, so writing through it is undefined behaviour and often a segmentation fault. Declaring a char array instead, as in char s[] = "hello";, copies the characters into writable stack storage and makes the same assignment legal. Compilers do not insert a heap copy, which is why the mistake survives compilation but crashes at run time.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is A? Ask here and get an explanation.