Is strncpy() secure for iPhone development?
If not, what is a better String API to use that is recommended to be secure?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you know the limitations of
strncpy(), then it is OK. I avoid it because I don’t like its limitations, which are two-fold:This means that if you write:
Then
littleis not a null-terminated string, though no buffer overflow has occurred, and large had 20454 nulls copied to its tail end. Both are troublesome.strlcpy()andstrlcat()are available on iOS; they are on Mac OS X.If you’re coding in C++, you shouldn’t be using C strings at all, or only in the most limited circumstances where a system service requires the use, and then you should have a cover function (inline) that takes a C++ string and passes the
somestring.c_str()value to the system service.If you’re coding in Objective-C, you’ll use the NS* strings.
So, only consider
strncpy()if you are coding in C. Treat it with caution even so.I have a thesis (and I don’t lay any claim to novelty in it — I collected the idea from others):
strcpy(),strncpy(),strcat()andstrncat()safely if you know the lengths of the strings, both the target buffers and the source strings (and you know the foibles of the function you’re calling — quickly, what does the length passed tostrncat()represent?(1)).strcpy(); you can usememmove()(ormemcpy()).(1) The length is the space available in the target buffer after the current string is accounted for. So, to be able to use
strncat(), you must know how long the string is in the target string, and the total length available, so that you can havestrncat()skip over the initial segment of the string and then concatenate some or all of the second string. But, if you know that, you could have used:which would be ‘more efficient’ because it doesn’t involve skipping over the leading part of the string (which, incidentally, can lead to quadratic behaviour if you’re building a long string with lots of
strncat()orstrcat()operations). Or, given that you know all the sizes, you could usememmove():And, unless I’ve got an off-by-one error in code written on the spur of the moment, that avoids most of the problems with
strncat(). If you always usestrncat()with the first argument pointing to the null at the end of a string, it has its uses (and may be optimized in assembler. Otherwise, it is not a good choice — IMNSHO.