On Mon, Jan 09, 2023 at 08:39:44PM +0100, Hans-Bernhard Bröker wrote: > > Whatever the original intention was behind strncat, this seems like > > a reasonable way to use strncat based on its behaviour and documentation. > > It is not. > > The size argument exists to enable the caller to make sure that the > destination buffer is not overrun, and for that to be possible, the size > argument _must_ have a dependency on the size of that destination buffer. > It may depend on the input string length, too, but that must not be the only > dependency.
How can you be so sure why the size argument exists? I downloaded the Unix version 7 sources (from 1979) from here https://www.tuhs.org/cgi-bin/utree.pl?file=V7 and I can see strncat being called only twice in that source tree: $ grep strncat . -R ./usr/src/cmd/dumpdir.c: strncat(prefix, dir.d_name, sizeof(dir.d_name)); ./usr/src/cmd/login.c: strncat(homedir, pwd->pw_dir, sizeof(homedir)-6); (plus other matches) The third argument appears to be used for both the source argument (first match) and destination argument (second match). Any documentation I can see on strncat describes the behaviour of strncat, but not of the recommended usage. > If one's not going to do the work needed to compute the size argument > correctly, then strncat() cannot offer any benefit over strcat(), and one > might as well not bother using it. Not if strncat is used for an initial substring, as happens throughout install-info.c.