1. Home
  2. Computer Science MCQs
  3. C Programming
  4. What happens when a C program executes char *s = "hello"…

Added 30 Nov -0001

What happens when a C program executes char *s = "hello"; s[0] = 'H';?

  1. Undefined behaviour, because the literal is read-only Correct answer
  2. The literal is modified and prints "Hello"
  3. A copy on the heap is modified instead
  4. The compiler automatically allocates writable memory for the literal

Correct answer

A. Undefined behaviour, because the literal is read-only

13 views

MCQSEXAM

Explanation

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.

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