|
|
|
|
|
by bboreham
2920 days ago
|
|
> 'strcpy' should usually be replaced by 'strncpy' Sorry to butt in, but this is a bit of a trigger for me: I’ve had to fix a number of programs infected with this idea. The main problems with strncpy are: When the source string is shorter than n, strncpy will pad the target to n bytes, filling with zeros. This is bad for performance. When the source string is longer than n, strncpy will copy n bytes but _not_ nul-terminate the target. So you need extra schenanigans every time you use it to cover this case. So strncpy is hardly ever a good idea. Sadly there is no standard replacement that is widely accepted. More details at
https://en.wikipedia.org/wiki/C_string_handling#Replacements |
|
Before writing to the buffer you should've ensured that it's big enough, and decided what to do if it's not, long before actually doing it. In other words, what happens if it's not big enough? These "always use $length_checking_function" proponents miss that point. Yes, you've avoided an overflow here, but chances are something was already too small long before the flow reached here, and the fix is not to replace an overflow with truncate/not copy/etc. here, but fix the check/sizing that came before elsewhere.