[prog] C++ Problem
Robert J. Hansen
rjh at sixdemonbag.org
Mon Apr 7 18:17:51 EST 2003
> Your original response was commenting on style. Using strncpy implies
> that you don't know whether the source string is null terminated. But you
> are not _always_ gauranteed that the size of the source and destination
> strings are known. Thus, it is unsafe. In this example, you got away
This (IMO) exposes a weakness of C rather than a weakness of what I was
proposing. It seems that with C, you get a choice between something
that's riotously unsafe (strcpy, without any sanity checks), something
that's safe but requires a modest degree of knowledge about the data
(strncpy), or something that's aesthetically inelegant (strcpy + macros
-- like many C++ programmers, I think macros are generally better
avoided if at all possible).
It's really a case of pick-your-poison: if you're going to be doing C
string handling, you've basically got a choice of different ways to
shoot yourself in the foot. The trick is finding the way which hits
your foot with the least frequency, and one which won't take off your
entire leg at the knee when it does hit.
> In my opinion, style wise, it is better to use a macro for the string
> size, and always null terminate your strings (making sure you don't
> overflow your buffers first). Then use strcpy to copy/move the string.
Other options--and I'm not especially married to either of these ideas,
but as long as we're tossing around alternatives--
* memset() all allocated memory to NULL. The impact on performance is
minimal, and it ensures that even if a source string isn't
null-terminated, the block of memory that it's copied into will be.
* I've also written hacked-up C string-handling routines which
overallocate four bytes of memory at the front of the block, and as
things are copied into/out of these blocks the unsigned long at the
front of it is updated with the string's current length--it's a
grotesque hack, but there are some problem sets where doing this can
give order-of-magnitude speedups (strlen becomes O(1) instead of O(n),
for instance). I certainly don't recommend it as a general-purpose
solution, but sometimes it's useful.
> When it comes to style, people are more concerned with whether there is a
> space after a comma than things like this. This is not directed at you
> specifically, Robert. But I do notice that many style guides lack
> attention to this type of issues.
Oh, agreed. I once had a job where I was singled out for management
criticism because my code was indented with four spaces instead of a
single tab character. Utterly ridiculous.
Robert J. Hansen <rjh at sixdemonbag.org>
More information about the Programming