Originally Posted by
cpjust
You should also avoid using strcpy(), strcat()... and use the 'n' versions instead (i.e. strncpy(), strncat()...), otherwise you could have a buffer overflow if you're not careful.
If you are using sequences of strcpy() and strcat() to build up a string, it's better to just use snprintf(). Look at this mess:
Code:
strcpy(full_name, last_name);
strcat(full_name, ", ");
strcat(full_name, first_name);
strcat(full_name, " ");
strcat(full_name, middle_name);
What if you wanted to make this safer by using the strncpy() and strncat() functions? You'd have to:
Code:
strncpy(full_name, last_name, sizeof(full_name));
strncat(full_name, ", ", sizeof(full_name) - strlen(full_name));
strncat(full_name, first_name, sizeof(full_name) - strlen(full_name));
strncat(full_name, " ", sizeof(full_name) - strlen(full_name));
strncat(full_name, middle_name, sizeof(full_name) - strlen(full_name));
And that's still not safe because strncpy() and strncat() may not place a null terminator in some cases! Compare with snprintf():
Code:
snprintf(full_name, sizeof(full_name), "%s, %s %s", last_name, first_name, middle_name);
snprintf() DOES guarantee a null terminator, it is more efficient (since it doesn't traverse the string over and over with each strcat() ) and it makes it clear what you are actually doing -- formatting a string.