Linkers, Loaders & Executables

Running C code "char *p = "hello"; p[0] = 'H';" crashes in many environments. Why?

  1. AThe string was on the stack and had vanished when the function returned
  2. BString literals are placed in read-only .rodata, and the code tried to write there
  3. 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.
Practice this topic Back to topic

More Linkers, Loaders & Executables questions

  1. Of the global variables above, which are generally placed in the .bss section?
  2. Where is a non-static local (automatic) variable declared inside a C function placed at run time?
  3. Memory allocated with C's malloc generally comes from which area of a process?
  4. Which lists the typical memory layout of a process on Linux and similar systems from low to high addresses?
  5. What is the advantage of laying out the heap and stack so they grow in opposite directions with a large gap between them?