Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.c Subject: Re: How to copy a string safely and efficiently in C? Date: Fri, 02 Sep 2016 10:42:01 +0100 Organization: A noiseless patient Spider Lines: 24 Message-ID: <87fupitz86.fsf@bsb.me.uk> References: <0b30b0cc-f7c5-4928-8acb-56bf2364797b@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="3334"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18VVJ29+29Ftfcc2zqzKx9X548cLDN3F7g=" Cancel-Lock: sha1:Mi+G2cAYzVHsGVvddXyHWGuSyx4= sha1:m1O/JQ4dnP9TTe8K+rwxFGEzIDg= X-BSB-Auth: 1.a2f71e99043f7f744443.20160902104201BST.87fupitz86.fsf@bsb.me.uk Xref: csiph.com comp.lang.c:93100 will hunt writes: > should I use strncpy or snprintf, and why? ...(from the subject line) to copy a string safely and efficiently in C? I vote for neither. Several people have explained why strncpy is out -- never use it unless you know its dangerous peculiarities happen to be *exactly* what you need -- but snprintf, though safe, is rather complicated for the job and requires a relatively recent C library. One simple solution is to use strncat(dst, src, n). This concatenates two strings by adding at most n characters from src to those already present in dst. To use it for copying, dst must contain an empty string, and you need to remember that a terminating null byte is added in addition to the characters that get copied. This means you would write something like this char copy[STR_SIZE]; *copy = 0; strncat(copy, src, STR_SIZE - 1); -- Ben.