Re: A stupid strcpy error...

From: Jason Wilkins (fenix@IO.COM)
Date: 09/22/98


Nick Stout wrote:

> When it did, it would give me an "error in strcpy" in the core.

This is the main reason why I decided to ALWAYS uses "strncpy"
and "strncat." Also on the banned list is "gets," I always use "fgets".  I
do not
trust myself in programming, or the users of my software enough to use
these
functions because they can overwrite the buffer if I ever changed
the strings without changing the size of the buffer, or my users
could maliciously use an errant strcpy to overwrite a buffer with
executable code (like the recent Netscape/Outlook scare).

This is sort of a "religous" thing.  Kinda pendatic.  But, better
safe than sorry.  The first thing I would do with that code snippet
is rewrite the dangerous versions of those functions with the
safer versions.  The value of 'n' should be calculated so that
you are guaranteed not to overwrite the end of the buffer.

A tip when you use strncpy and strncat.  ALWAYS do
something like this:

strncpy(buf, string, n)
buf[n] = '\0';

Don't bother with an if statement, like if(n = BUFLEN) ...; Its faster
just to do it everytime.

The reason is because these functions will not copy the terminating NUL
character if the string being copied is longer than the buffer.

Another thing, just for those that have not thought about it the "NUL"
character, and NULL are not the same thing.  It only matters on
systems that do not use 0 to represent a NULL pointer (strangely,
sum systems don't).  If you compared '\0' with NULL on one of these
systems it would not match.  However, on most systems they are
the same.  In other words, NULL == '\0' is not always true.

Anyway, If you are getting a segmention fault/access violation/protection
fault it is most likely a buffer overrun because strcpy is writing past the
end
of the string. If its not that then it may be in another place in the code.

That is causing the NUL character at the of one of these strings to be
overwritten, so that when you do a strcat, it just keeps going and going
looking for the end of the string, and stops only when it hits the top of
memory (the break) and causes a protection fault.

--
           Phoenix -- President of The Artistic Intuition Company
       Caelius * Mirror Reflex * Runica * X-Domain * Infinite Realms
                          http://www.io.com/~fenix


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST