Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added ECLAIR among the tools that support this rule.

...

In C, function arguments are passed by value rather than by reference. While a function may change the values passed in, these changed values are discarded once the function returns. For this reason, many programmers assume a function will not change its arguments, and declaring the function's parameters as const is unnecessary.

Code Block

void foo(int x) {
  x = 3; /* persists only until the function exits  */
  /* ... */
}

Pointers behave in a similar fashion. A function may change a pointer to reference a different object, or NULL, yet that change is discarded once the function exits. Consequently, declaring a pointer as const is unnecessary.

Code Block

void foo(int *x) {
  x = NULL; /* persists only until the function exits  */
  /* ... */
}

...

Code Block
bgColor#FFCCCC
langc

void foo(int *x) {
  if (x != NULL) {
    *x = 3; /* visible outside function */
  }
  /* ... */
}

...

Code Block
bgColor#ffcccc
langc

void foo(const int *x) {
  if (x != NULL) {
    *x = 3; /* generates compiler error */
  }
  /* ... */
}

...

Code Block
bgColor#ccccff
langc

void foo(const int * x) {
  if (x != NULL) {
    printf("Value is %d\n", *x);
  }
  /* ... */
}

...

Code Block
bgColor#FFCCCC
langc

char *strcat_nc(char *s1, char *s2);

char *str1 = "str1";
const char *str2 = "str2";
char str3[9] = "str3";
const char str4[9] = "str4";

strcat_nc(str3, str2);	/* Compiler warns that str2 is const */
strcat_nc(str1, str3);  /* Attempts to overwrite string literal! */
strcat_nc(str4, str3);  /* Compiler warns that str4 is const */

...

Code Block
bgColor#ccccff
langc

char *strcat(char *s1, const char *s2); 

char *str1 = "str1";
const char *str2 = "str2";
char str3[9] = "str3";
const char str4[9] = "str4";

strcat(str3, str2); 

/* Args reversed to prevent overwriting string literal */ 
strcat(str3, str1);  
strcat(str4, str3);  /* Compiler warns that str4 is const */

...

Tool

Version

Checker

Description

Section

Compass/ROSE

 

 

Section

can detect violations of this recommendation while checking for violations of recommendation DCL00-C. Const-qualify immutable objects

Section

LDRA tool suite

Include Page
LDRA_V
LDRA_V
Section

62 D

Section

Fully Implemented

Section

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V
Section

cnstpnte

Section

Fully Implemented

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...