[prog] C++ Problem

Jimen Ching jching at flex.com
Sun Apr 6 18:05:19 EST 2003


On Sun, 6 Apr 2003, Robert J. Hansen wrote:
>> void InitialiseVehicle (Vehicle *a, char name[20])
>> {
>>         a->vehicle_name, name;
>Bug:
>strncpy(a->vehicle_name, name, 19);
>Alternate fix:
>strcpy(a->vehicle_name, name);
>
>(strncpy is overwhelmingly the preferred solution, though, and for good
>reason.)

Preferable for the C language, I assume?  I would imagine for C++, most
would prefer your suggestion of std::string.

But even for C, strncpy is not safer than strcpy for a new programmer.
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
in trouble.

For new C programmers, my advice to you is to use a constant macro for the
size of the name variables.  Then use strcpy to move data around.  The
only place where I would use strncpy is if I knew the source string is at
least, or larger than the number of characters I want to copy.  I.e. if I
knew I had a string that is more than 4 characters, and I only want the
first four characters.  I would not use strncpy for any other reason.

The alternative is to detect the smaller of the two parameters to strncpy,
which is not always possible.

Aside from this, I agree with everything else Robert said in his email.

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


More information about the Programming mailing list