Re: strncpy() fails to copy



On Sep 14, 10:03 am, David Resnick <lndresn...@xxxxxxxxx> wrote:
On Sep 14, 9:57 am, Tom St Denis <t...@xxxxxxx> wrote:





On Sep 14, 9:52 am, David Resnick <lndresn...@xxxxxxxxx> wrote:

On Sep 14, 9:16 am, Tom St Denis <t...@xxxxxxx> wrote:

So as you correctly pointed out (and David Resnick got wrong) you need
to -1 the sizeof of the buffer.

Yep, oops.  Don't use either much at this point.  Still thing strncpy
is awful tho.

Since you still have to use -1 on strncat how is it any different than

dest[sizeof(dest)-1] = 0;
strncpy(dest, src, ...);

It's basically the same code at that point.

It'd be nice if all strn*() functions guaranteed that within n-bytes
of the dest there is a NUL and just truncate as required.  But that
would require a bit of forethought on the standard C library designers
part.

Tom

Again, because strncpy has a design second flaw for general purpose
string usage, that it internally does a stupid memset that can be
QUITE costly if the target buffer is big and the string to be copied
is small.

In my current app I'm more worried about buffer overflows or corrupt
[uninitialized] strings than a few microseconds of performance.

But as I said you *could* just set the n-1'th byte to 0 and get the
same effect.

Tom
.



Relevant Pages

  • Re: Function Points
    ... I should've compared with strncpy() instead of strcpy. ... strncpyalso copies into a buffer of unknown size, ... of that string actually is, so strncat is not that helpful. ... I'm not sure if these are the type of hash functions they need, ...
    (comp.lang.forth)
  • Re: Discovering variable types...
    ... >- but I suppose MS expect us to use wrappers ... memory allocations for your variables from disk as well. ... >They most certainly are of fixed size, changing the size of a String ... >>me to keep buffer size and current postion right in the memory block. ...
    (comp.lang.pascal.delphi.misc)
  • Re: Secure C library
    ... I read much of the new "security TR", and gee, I don't know. ... the buffer from the buffer size. ... It is not hard to design a better form of buffer and string handling. ... but this is just one example of how thoughtful interface design can ...
    (comp.std.c)
  • Re: Secure C library
    ... >> string functions don't make much sense once you add bounds-checking ... >> designing an interface just for the purpose of reducing the frequency ... > make buffer size decisions more visible, ... Bstrlib is also very interoperable with char *'s, ...
    (comp.std.c)
  • Re: Calling dll functions from vb.net with pointer returns!
    ... (ByRef pulLen As Integer, ByVal pszFilter As String, ByVal ulFlags As ... OUT PTCHAR Buffer, ... Address of a buffer to receive a set of NULL-terminated device instance ... pszFilter must specify the name of a device ...
    (microsoft.public.dotnet.languages.vb)