writeable constant strings

Another one of those silly problems in C programming that occasionally crops up.
Depending on the compiler, declaring a char * variable pointing to a string constant can cause that string to go into the .text segment of the application. This segment is marked as readable and executable; but explicitly not writeable.
When you try to write to this address it issues a memory protection fault (SEGV on linux). Solutions are:

  1. copy the string using strdup before writing to it. This means you need to remember to free the memory once the function has completed.
  2. use alloca and strcpy to populate the string. This eliminates the need to free the memory, but adds a bit to the set-up overhead

Nontheless, you should never be writing to values obtained from a constant; you never know where it's been (poor blighter).

About this Entry

This page contains a single entry by Pete Shanahan published on August 18, 2004 1:50 AM.

beaming was the previous entry in this blog.

beaming - first draft is in is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.