Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The correct solution depends on the original programmers intent. If your intent was to truncate a string but ensure that the
result was a null-terminated string the following solution can be used.

Code Block
char a[16];
strncpy(a, "0123456789abcdef", sizeof(a)-1);
a[sizeof(a)] = '\0';

Compliant Solution 2

...

If the intent is to copy without truncation, this example will copy the data and guarantee that the resulting null-terminated byte string is null-terminated. If the string cannot be copied it is handled as an error condition.

Code Block

#define A_SIZE 16
char *string_data;
char a[A_SIZE];
...
if (string_data) {
  if (strlen(string_data) < sizeof(a)) {
    strcpy(a, string_data);
  }
  else {
    /* handle string too large condition */
  }
}
else {
  /* handle null string condition */
}

Compliant Solution 3

Example using strncpy_s()

The strncpy_s function copies not more than n successive characters (characters that
follow a null character are not copied) from the array pointed to by s2 to the array
pointed to by s1. If no null character was copied from s2, then s1n is set to a null
character.

Exception

An exception to this rule applies if the intent of the programmer was to convert a null-terminated byte string to a character array.  To be compliant with this standard, this intent must be made clear statement in comments.

...