gnokii-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [PATCH] Kill strcpy and strcat


From: Pawel Kot
Subject: Re: [PATCH] Kill strcpy and strcat
Date: Wed, 7 Nov 2007 16:22:44 +0100

Hi,

On Nov 7, 2007 2:37 PM, Philip Kendall <address@hidden> wrote:
> On Wed, Nov 07, 2007 at 02:26:40PM +0100, Pawel Kot wrote:
> >
> > Maybe somebody could tell me if there is a difference between:
> > snprintf(buf, sizeof(buf), "%s", some_string);
> > and
> > strncpy(buf, some_string, sizeof(buf));
> > buf[sizeof(buf) - 1] = 0;
>
> There's the obvious difference that if strlen(some_string) <
> sizeof(buf) - 1 then the snprintf() version won't set
> buf[sizeof(buf) - 1] to zero, but I can't see how this makes any
> difference in any real world use.

What matters is that the string should be NULL terminated. The strncpy
version should in fact look like:
strncpy(buf, some_string, sizeof(buf));
if (strlen(some_string) >= sizeof(buf))
  buf[sizeof(buf)-1] = 0;

> strncpy() is presuambly more efficient as well.

As Ian points out and as manual page says:
    If the length of src is less than n, strncpy() pads the remainder
of dest with null bytes.
So I'd say, strncpy may be less efficient (when the string is
seemingly shorter than the buffer itself).

take care,
pkot
-- 
Pawel Kot




reply via email to

[Prev in Thread] Current Thread [Next in Thread]