Strings

Contents

Strings#

A C string is a null-terminated char array (or a pointer to one). The terminating \0 is not counted in strlen but is required by every string-handling function.

const char *s = "hello";
size_t n = strlen(s);        /* 5; does not count \0 */
char buf[64];
strncpy(buf, s, sizeof buf - 1);
buf[sizeof buf - 1] = '\0';  /* always terminate manually */

Use strncpy / snprintf / strlcpy (BSD), never strcpy / strcat / gets. The unsafe forms are the source of more CVEs than any other class of bug in C history.

References#