Copying strings

suggest change

Assigning a character pointer copies an address; it does not copy the characters. Arrays cannot be assigned at all:

char text[] = "abc";
char *alias = text;

text[1] = 'x';
printf("%s\n", alias); /* Prints "axc". */

To copy a string into an array, first prove that the array has room for every character plus the terminating null character. strcpy performs no bounds check:

char source[] = "abc";
char destination[8];

if (strlen(source) + 1 > sizeof destination) {
    /* Handle a destination that is too small. */
} else {
    strcpy(destination, source);
}

When truncation is acceptable, snprintf always terminates the destination if its capacity is nonzero. Its return value reveals whether truncation occurred:

char destination[8];
int length = snprintf(destination, sizeof destination, "%s", source);

if (length < 0) {
    /* Encoding or formatting error. */
} else if ((size_t)length >= sizeof destination) {
    /* The result was truncated. */
}

If the source length is already known, a checked memcpy avoids parsing a format string:

size_t length = strlen(source);
if (length < sizeof destination) {
    memcpy(destination, source, length + 1);
}

Do not treat strncpy or strncat as automatically safe alternatives. strncpy may leave the destination unterminated and pads unused space with null bytes. The limit passed to strncat is the maximum number of source characters to append, not the destination capacity, so the caller must still calculate the remaining space correctly.

For concatenation, snprintf can express the complete operation and report truncation:

char destination[24];
int length = snprintf(destination, sizeof destination,
                      "%s%s", "Clownfish: ", "Marvin and Nemo");
if (length < 0 || (size_t)length >= sizeof destination) {
    /* Handle an error or a truncated result. */
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents