Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: example cleanup

...

This code example is noncompliant because the character sequence c_str will not be null-terminated when passed as an argument to printf().  See STR11-C. Do not specify the bound of a character array initialized with a string literal.

Code Block
bgColor#FFcccc
langc
#include <stdio.h>
 
void func(void) {
  char c_str[3] = "abc";
  printf("%s\n", c_str);
}

Compliant Solution

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 
void func(void) {
  char c_str[] = "abc";
  printf("%s\n", c_str);
}

Noncompliant Code Example

...

Code Block
bgColor#FFcccc
langc
#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];

  c_str[sizeof(c_str) - 1] = '\0';
  strncpy(c_str, source, sizeof(c_str));
  return strlen(c_str);
}

Compliant Solution (Truncation)

...

Code Block
bgColor#ccccff
langc
#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];

  strncpy(c_str, source, sizeof(c_str) - 1);
  c_str[sizeof(c_str) - 1] = '\0';
  return strlen( c_str);
}

Compliant Solution (Copy without Truncation)

...

Code Block
bgColor#ccccff
langc
#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];

  if (source) {
    if (strlen(source) < sizeof(c_str)) {
      strcpy(c_str, source);
    } else {
      /* Handle string-too-large */
    }
  } else {
    /* Handle null pointer */
  }
  return strlen(c_str);
}

Compliant Solution (strncpy_s(), C11 Annex K)

...