Hacker News new | past | comments | ask | show | jobs | submit login

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.



This is about maintaining invariants, and I interpret the "any random input" from the parent question as "input that breaks the preconditions the function expects of its inputs."

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?


THIS!

It would've been nice if C came with real string support, but it didn't. Instead, we're stuck mucking around with character arrays. All the built-in functions expect null-terminated strings, but many functions don't guarantee they'll generate these strings in all cases.

Look at strncpy. If the string you're copying fills the destination buffer completely, the function won't write the null terminator; the resulting string will blow up several C standard library functions.

If you're using null-terminated strings, it is your job to make damn sure those strings are always null-terminated.

C is an unsafe language. Get used to it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: