Versions Compared

Key

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

...

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 = "0123456789abcdef";
char a[A_SIZE16];
...
if (string_data) {
  if (strlen(string_data) < sizeof(a)) {
    strcpy(a, string_data);
  }
  else {
    /* handle string too large condition */
  }
}
else {
  /* handle null string condition */
}

...

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 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.

...