Versions Compared

Key

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

...

Include Page
c:STR33 CS 3
c:STR33 CS 3

Non-Compliant Code Example

The standard functions strncpy() and strncat() do not guarantee that the resulting string is null terminated.  If there is no null character in the first n characters of the source array, the result may not be null-terminated, as in this example:

Code Block

char a[16];
strncpy(a, "0123456789abcdef", sizeof(a));

Compliant Solution 1

The correct solution depends on the programmer's intent. If the intent was to truncate a string but ensure that the result was a null-terminated string, this 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

char *string_data = "0123456789abcdef";
char a[16];
...
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

The strncpy_s() function copies not more than a maximum number n of successive characters (characters that follow a null character are not copied) from the source array to a destination array. If no null character was copied from the source array, then the nth position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.

This compliant solution also guarantees that the string is null-terminated.

Code Block

#define A_SIZE 16

char *string_data;
char a[A_SIZE];
...
if (string_data) {
  strncpy_s(a, sizeof(a), string_data, 5);
}
else {
  /* handle null string condition */
}

Exception

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

...