Strings in C: pitfalls and techniques
c, string
Solution
It's obvious but I think it's important to know that strings are nothing more than an array of bytes, delimited by a zero byte. C strings aren't all that user-friendly as you probably know.
- Writing a zero byte somewhere in the string will truncate it.
- Going out of bounds generally ends bad.
- Never, ever use strcpy, strcmp, strcat, etc.., instead use their safe variants: strncmp, strncat, strndup,...
- Avoid strncpy. strncpy will not always zero delimit your string! If the source string doesn't fit in the destination buffer it truncates the string but it won't write a nul byte at the end of the buffer. Also, even if the source buffer is a lot smaller than the destination, strncpy will still overwrite the whole buffer with zeroes. I personally use strlcpy.
- Don't use printf(string), instead use printf("%s", string). Try thinking of the consequences if the user puts a %d in the string.
- You can't compare strings with
if( s1 == s2 )
doStuff(s1);
You have to compare every character in the string. Use strcmp or better strncmp.
if( strncmp( s1, s2, BUFFER_SIZE ) == 0 )
doStuff(s1);
Problem
I will be coaching an ACM Team next month (go figure), and the time has come to talk about strings in C. Besides a discussion on the standard lib, `strcpy`, `strcmp`, etc., I would like to give them some hints (something like `str[0] is equivalent to *str`, and things like that). Do you know of any lists (like cheat sheets) or your own experience in the matter? I'm already aware of the books for the ACM competition (which are good, see particularly this), but I'm after tricks of the trade. Thank you. Edit: Thank you very much everybody. I will accept the most voted answer, and have duly upvoted others which I think are relevant. I expect to do a summary here (like I did here, asap). I have enough material now and I'm certain this has improved the session on strings immensely. Once again, thanks.