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) */
- A. (i)
- B. (iii)
- C. (ii)
- 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
- What is printed? c int calls = 0; int C(int n, int k) { calls++; return (k == 0 || k == n) ? 1 : C(n - 1, k - 1) + C(n - 1, k); } int…
- What is printed? c enum E { A = -2, B, C, D = A + 10, E2 }; printf("%d %d %d", B, C, E2);
- What is printed? c int steps(int n) { return n == 1 ? 0 : 1 + steps(n % 2 ? 3 n + 1 : n / 2); } int main(void) { printf("%d %d", steps(6)…
- Assume ASCII. What does f("Code21") print? c void f(const char s) { if (s) { f(s + 1); if (s % 2) putchar(s); } }
- What is printed? c int a = 1, b = 2, c = 3; int arr[] = {&a, &b, &c}; int pp = arr + 1; pp += 10; pp[1] += 20; printf("%d %d %d", a, b, c);
- Assume 32-bit unsigned int. What is printed? c unsigned mask(int lo, int hi) { return ((1u << (hi - lo + 1)) - 1) << lo; } int main(void)…