ProgrammingModerateTCS NQT · Product company OA

Which line has undefined behaviour?

Which line has undefined behaviour?
char a[] = "hi";
char *p = "hi";
a[0] = 'H';          /* (i)   */
p[0] = 'H';          /* (ii)  */
char *q = a; q[1] = 'I';    /* (iii) */
const char *r = "hi"; r = a;  /* (iv)  */
  1. A. (i)
  2. B. (iii)
  3. C. (ii)
  4. D. (iv)

Correct answer: C. (ii)

a is an ordinary array initialised from the literal, so (i) and (iii) modify a copy. p points at the string literal itself, and modifying a string literal is undefined (it often crashes, as literals sit in read-only memory). (iv) only changes which string r points to.

More C Programming questions

Exams that ask this topic