1. Home
  2. Computer Science MCQs
  3. C Programming
  4. char *p = "hello"; p[0] = 'H'; is executed. What is the…

Added 30 Nov -0001

char *p = "hello"; p[0] = 'H'; is executed. What is the status of this program under the C standard?

  1. Undefined behaviour, because the string literal has static storage and must not be modified Correct answer
  2. It is well defined, but only on little-endian machines and only when the optimisation is disabled
  3. It works as intended, because p is a non-const pointer that points at a writable array
  4. It is a syntax error, because string literals cannot be indexed or assigned through any pointer

Correct answer

A. Undefined behaviour, because the string literal has static storage and must not be modified

16 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs