login
Header Space

 
 

Re: [PATCH] locomo.c: convert strncpy(x, y, sizeof(x)) to strlcpy

Score:
Previous message: [thread] [date] [author]
Next message: [thread] [date] [author]
To: H. Peter Anvin <hpa@...>
Cc: <elf@...>, Linux-arm <linux-arm-kernel@...>, lkml <linux-kernel@...>
Date: Thursday, March 6, 2008 - 7:35 pm

H. Peter Anvin wrote:

As I understand it, please correct me if I'm wrong:

Of the three variants: strcpy, strncpy and strlcpy.
- strcpy does not append \0 (unless the source string already contained it)
- strncpy appends \0's if the source string is smaller than the size
  parameter (for all remaining characters)
- strlcpy always appends a single \0 (unless size parameter was 0)

char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
size_t strlcpy(char *dst, const char *src, size_t n);

In the original code strncpy was used and the size parameter was equal
to the source string size:

strncpy(dev->dev.bus_id, info->name, sizeof(dev->dev.bus_id));

Since this the size was equal there was no \0 termination. To \0
terminate using strncpy we could write:

strncpy(dev->dev.bus_id, info->name, sizeof(dev->dev.bus_id) - 1);
dev->dev.bus_id[sizeof(dev->dev.bus_id) - 1] = '\0';

or using strlcpy, which does the same thing:

strlcpy(dev->dev.bus_id, info->name, sizeof(dev->dev.bus_id));

Roel
--
Previous message: [thread] [date] [author]
Next message: [thread] [date] [author]

Messages in current thread:
Re: [PATCH] locomo.c: convert strncpy(x, y, sizeof(x)) to st..., Roel Kluin, (Thu Mar 6, 7:35 pm)
speck-geostationary