[OCLUG-devel] strcpy segmentation faults

Christopher Smith x at xman.org
Tue Jun 21 13:36:24 PDT 2005


Doug Jolley wrote:
> Hi.  I'm very green but I'm really trying to learn C.  I seem to keep
> coming up with segmentation fault errors and they always seem to occur
> within the context of a strcpy.

Keep in mind that strcpy is a fairly dangerous function, as it will just
keep going if it doesn't find a null byte. It's safer to use strncpy().
In this case it's pretty much a non-issue as you're already using
strstr() which relies on the null byte being there as well.

>  I am appending an example function I
> wrote that is intended to remove the beginning part of a string up to
> the first occurrence of an underscore (_).  I'm getting a segmentation
> fault and the strcpy seems to be the culprit.  I am having similar
> problems elsewhere.  Aside from wanting to know what my specific
> problem is in this case, I'm wondering what is the best procedure for
> trouble shooting segmentation faults.

Generally, the best procedure is to load up the core file in gdb.
That'll show you what specifically caused the fault, and then look at
what it was accessing that was of memory. Then back trace through the
stack to figure out how that happened. Alternatively, just run the thing
in gdb from the get go. That tends to produce the best results, but
everything runs more slowly.

> Thanks for any input.  Here is
> the example:
> 
>  char *trim(char *p2c)
>  {
>   char *ptr1;
>   /* If p2c contains an '_', trash it and any characters that prceed it. */
>   ptr1=strstr(p2c,"_");
>   if (ptr1!=NULL)
>     strcpy(p2c,ptr1+1);
>   return p2c;
>  }

Hmm... maybe your is different, but my man page for strcpy specifically
says "The strings may not overlap" in the second sentence. ;-)

That is what's causing your core dump.

Note also that you are finding the first "_" and not the last. To find
the last "_" use strrchr() instead of strstr. Even if you want the
first, since the pattern you're matching against is a single character,
I'd recommend using strchr().

--Chris


More information about the OCLUG-devel mailing list