|
|
|
|
|
by jballanc
5265 days ago
|
|
This is a borderline straw-man argument. Size (length) is one of the few things that you must be very aware of and control when programming C. You cannot "malloc" without knowing the length to malloc. You cannot create an array on the stack without knowing its size. In each case, you may not use the full memory allocated, but at least you can set an upper bound on the memory that you own. Thus, however you created or ingested the string to copy (and the memory to copy it to), you will have an upper bound on how much memory it is safe to copy. |
|
With str* functions the assumptions are that the string is null-terminated and stored within a memory block of large enough size.
When providing string+length, "any random input" means that, e.g., length may be arbitrary; maybe it became garbage as a consequence of series of unfortunate integer overflows (when did you last check for those when checking that len1+len2 < buffer_size ?).
So, how DO you write a string-handling function that can safely handle ANY random input?