[OCLUG-devel] strcpy segmentation faults

Christopher Smith x at xman.org
Tue Jun 21 17:23:01 PDT 2005


I thought of another reason you might be having troubles with your code.
 Modern versions of gcc make all string constants actually constant, and
if you modify them in any way, you get a segfault. So for example you'll
get a segfault if you do trim("hello_world") as soon as you try to
overwrite that 'h' with a 'w'. So, you need to make a copy of the string
first.

In general, since you are trying to do an in place modification of the
string (not sure how good an idea that is, but there is merit to it
depending on the situation), I'd not use strcpy, strncpy, or memcpy at
all. Instead I'd just do it manually:

char* trim(char* p2c)
{
  /* copy the pointer so that we still have something to return to */
  char* target_iter = p2c;
  char* source_iter;
  /* If p2c contains an '_', trash it and any character that proceed it. */
  source_iter = strrchr(p2c, '_');
  if (source_iter != NULL) {
    do {
      *target_iter++ = *++source_iter;
    } while (*source_iter != '\0');
  }

  return p2c;
}


More information about the OCLUG-devel mailing list