[Swan] strncpy doesn't do what many people think that it does

D. Hugh Redelmeier hugh at mimosa.com
Fri Feb 15 07:30:33 EET 2013


| From: Wes Hardaker <opensource at hardakers.net>

| > 	assert(n != 0);		/* won't hold a string! */
| 
| Asserts are pure evil in production servers.  They cause important
| software to go down and are an easy spot for denial of service attacks.
| The better thing to do is return an error code, let the above code catch
| and handle it and keep running.

I understand your point.

BTW, I wrote "assert", which is generic, not "passert" which is what
would be used in Pluto.  That was a too-subtle hint that this was
schematic.

Furthermore, I also said silent truncation is almost never what is
wanted.

However: the number of unchecked failure returns in C code is really
really high and a scandal.  It is time to realize that humans can't
get this checking right -- we need help.  I don't have a simple 
suggestion to fix this.

The right way to call this code is to check/prove length>0 as a
precondition, not check for failure after the fact.  The assert is a
safety mechanism.

Shame on me for not documenting the precondition.  It's tricky.
	src != NULL
	&& src points at a string
	&& dest != NULL
	&& dest points at writeable memory of size >= len
	&& len > 0
I'm not sure that I got them all.  I'm not documenting the postcondition.

Notice that most hardware would do:
	assert(src != NULL);
	assert(dst != NULL);
	and more
So just because I don't write assert doesn't mean your goal is
reached.

(C really needs a pointer type that isn't allowed to contain NULL.  That 
would help compilers and programmers help each other.  I had a last-minute 
hack for C99 but it wasn't accepted.)


More information about the Swan mailing list