ProgrammingHardIBM · Deloitte pattern

Assume a 64-bit LP64 ABI. What happens when this runs?

Assume a 64-bit LP64 ABI. What happens when this runs?
char *str = "hello";
str[0] = 'H';
printf("%s", str);
  1. A. It prints Hello, with the first letter capitalised
  2. B. It prints hello, unchanged
  3. C. Undefined behaviour: str points at a read-only string literal, and modifying it is not allowed
  4. D. Compile-time error: string literals cannot be assigned to char*

Correct answer: C. Undefined behaviour: str points at a read-only string literal, and modifying it is not allowed

char *str = "hello"; makes str point at a string literal, which has static storage and is typically placed in read-only memory; attempting to modify it through str[0] = 'H' is undefined behaviour (often a segmentation fault on modern systems, but not guaranteed to crash everywhere). This is exactly why char str[] = "hello"; (a genuine, writable array copy) is used instead when modification is needed.

More C Programming questions

Exams that ask this topic