Re: safe strcpy()?

From: Ben Pfaff (blp@cs.stanford.edu)
Date: 01/30/03

  • Next message: Ed Carp: "Re: safe strcpy()?"
    To: <secprog@securityfocus.com>
    From: Ben Pfaff <blp@cs.stanford.edu>
    Date: 29 Jan 2003 15:40:16 -0800
    
    

    "Michael Howard" <mikehow@microsoft.com> writes:

    > The point I'm making is people seem to think they can write crap code,
    > then bindly replace the calls to strcpy with strncpy and all of a sudden
    > their code is safe. [...]

    The usual reason cited not to use strncpy() is that it doesn't
    necessarily null-terminate its output buffer. But there's at
    least one other reason: using strncpy() into a large buffer can
    be very inefficient. strncpy() always writes to every byte in
    the destination buffer, which can waste a lot of time if the
    destination buffer is much longer than the source string.

    As a result, strncpy() is hardly ever the right function to use.
    strlcpy() from OpenBSD is usually a better choice.

    -- 
    "If a person keeps faithfully busy each hour of the working day, he
     can count on waking up some morning to find himself one of the
     competent ones of his generation."
    --William James
    


    Relevant Pages

    • Re: [Lit.] Buffer overruns
      ... The "real" strncpy(): ... -- does NOT necessarily zero-terminate the destination string (if ... truncation occurs because the destination buffer is too short). ... bufwhich are overwritten by the strncat(). ...
      (sci.crypt)
    • Re: Need to find size of destination buffer for strncpy
      ... We are using strcpy to copy strings in our app. ... when the destination buffer is not large enough. ... wanted to replace calls to strcpy with strncpy. ...
      (comp.lang.c)
    • Re: Need to find size of destination buffer for strncpy
      ... We are using strcpy to copy strings in our app. ... when the destination buffer is not large enough. ... wanted to replace calls to strcpy with strncpy. ...
      (comp.lang.c)
    • Re: supplementary C frequent answers
      ... "Using strncpy() into a large buffer can be very inefficient. ... if the destination buffer is much longer than the source string." ... "The strncpy function copies not more than n characters (characters that ... As a general guidance, as e.g. on your website, it will ...
      (comp.lang.c)
    • Re: supplementary C frequent answers
      ... > "Using strncpy() into a large buffer can be very ... > time if the destination buffer is much longer than ... string that is shorter than n characters, ...
      (comp.lang.c)