[prog] C++ Problem

Jimen Ching jching at flex.com
Mon Apr 7 10:38:20 EST 2003

On Mon, 7 Apr 2003, Robert J. Hansen wrote:
>> Even your suggestion above is incorrect.  You assume a->vehicle_name is at
>> least as large as name.  If it were less than 20 characters, then you're
>I no longer have the original message, but weren't both fields declared
>as char[20]s?

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
with it because the code is in front of you.  You won't always have this

Also, if 'name' was not null terminated, neither will a->vehicle_name.
Now, any where that a->vehicle_name is used, a check is needed.  As
opposed to doing an initial check when the name was first obtained.

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.


P.S.  Not knowing; whether it's the presence of a string's terminator or
the size of a storage buffer, is the stuff that defects are made of.
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.

Jimen Ching (WH6BRR)      jching at flex.com     wh6brr at uhm.ampr.org

More information about the Programming mailing list