Linkers, Loaders & Executables
Running C code "char *p = "hello"; p[0] = 'H';" crashes in many environments. Why?
- AThe string was on the stack and had vanished when the function returned
- BString literals are placed in read-only .rodata, and the code tried to write there
- CBecause p was initialized to 0
Show answer and explanation
Answer: B. String literals are placed in read-only .rodata, and the code tried to write there
String literals such as "hello" and const global constants go in a read-only data area (.rodata). Writing to those pages is forbidden, so the CPU detects a protection fault and the OS stops the program (a segmentation fault). To modify the text, declare an array, "char s[] = "hello";", which makes a copy in writable memory.
- A. String literals last for the whole run.
- B. Correct. The write causes a protection fault.
- C. p points to the start of the string.