From: Stephen Lewis Date: 2003-03-31T07:14:11+09:00 Subject: [OT] Re: Article on secure code --rRahWmzs6g95=.N3 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit On Mon, 31 Mar 2003 07:06:46 +0900 Brian Candler wrote: > On Mon, Mar 31, 2003 at 06:10:46AM +0900, gabriele renzi wrote: > Incidentally, snprintf is actually rather painful to use safely. I > originally wrote some code like this: > > char buf[256]; > int len = 0; > len += snprintf(buf+len, sizeof(buf)-len, ...); > len += snprintf(buf+len, sizeof(buf)-len, ...); /* etc */ > > You'd think that would work? It doesn't. In the event of the output > being truncated, snprintf actually returns the number of characters it > *would* have written to the string, if it had been given unlimited > space. Hence'len' still goes off the end of the string, and subsequent > snprintf's will write '\0' to bits of memory which they shouldn't :-( This is in fact the ideal behaviour if you're using dynamically allocated storage - you do one speculative snprintf, if that fails, realloc the buffer and snprintf again. Very handy. The problem is, the return value of snprintf tends to vary between platforms, so you can't really use it for anything useful in portable code. -- Stephen Lewis slewis@paradise.net.nz --rRahWmzs6g95=.N3 Content-Type: application/pgp-signature -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+h2t1IgTEtLC7U/IRAm4jAJ9Z2t2zaHUm5f7a0WGzEWj5/R6PUQCgtpEs pWg3L77ZVaQ7YqUSFvbGAp4= =gmiA -----END PGP SIGNATURE----- --rRahWmzs6g95=.N3--