strncpy is not a safe version of strcpy - Mailing list pgsql-hackers

From David Rowley
Subject strncpy is not a safe version of strcpy
Date
Msg-id CAApHDvoKSa-2yjdSfoFk8bC8A4QGfFb3f5R3LETJ_h_-Of1dPg@mail.gmail.com
Whole thread Raw
Responses Re: strncpy is not a safe version of strcpy  ("Tomas Vondra" <tv@fuzzy.cz>)
List pgsql-hackers
Hi All,

As a bit of a background task, over the past few days I've been analysing the uses of strncpy in the code just to try and validate if it is the right function to be using. I've already seen quite a few places where their usage is wrongly assumed.

As many of you will know and maybe some of you have forgotten that strncpy is not a safe version of strcpy. It is also quite an inefficient way to copy a string to another buffer as strncpy will 0 out any space that happens to remain in the buffer. If there is no space left after the copy then the buffer won't end with a 0.

It is likely far better explained here --> http://www.courtesan.com/todd/papers/strlcpy.html

For example , the following 2 lines in jsonfuncs.c

memset(name, 0, NAMEDATALEN);
strncpy(name, fname, NAMEDATALEN);

The memset here is redundant as strncpy will null the remaining buffer. This example is not dangerous, but it does highlight that there's code that's made the final cut which made this wrong assumption about strncpy.

I was not going to bring this to light until I had done some more analysis, but there was just a commit which added a usage of strncpy that really looks like it should be a strlcpy.

I'll continue with my analysis, but perhaps posting this early will bring something to light which I've not yet realised.

Regards

David Rowley

pgsql-hackers by date:

Previous
From: Tom Lane
Date:
Subject: Re: "union all" query consumes all memory
Next
From: Tom Lane
Date:
Subject: Anybody using get_eclass_for_sort_expr in an extension?