Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Minor edits

...

In this noncompliant example, the C Standard Library function strchr() is called through the function pointer fp with incorrectly typed arguments. According to the C Standard Standard, subclause 6.3.2.3 paragraph 8 [ISO/IEC 9899:2011],

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to the referenced type, the behavior is undefined.

...

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>
#include <string.h>

char *(*fp) ();

int main(void) {
  const char *c;
  fp = strchr;
  c = fp(12"Hello", 2'e');
  printf("%s\n", c);
  return 0;
}

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <string.h>

char *(*fp) (const char *, int);

int main(void) {
  const char *c;
  fp = strchr;
  c = fp("Hello",'He');
  printf("%s\n", c);
  return 0;
}

...

Code Block
bgColor#FFCCCC
langc
/* In another source file */
#include <string.h>
void copy(char *dst, const char *src) {
  if (!strcpy(dst, src)) {
    /* Report error */
  }
}
 
/* In this source file, no copy prototype in scope */
void copy();
 
void g(const char *s) {
  char buf[20];
  copy(buf, s, sizeof (buf));  /* Violation */
  /* ... */
}

...

Code Block
bgColor#FFCCCC
langc
/* In another source file */
void buginf(const char *fmt, ...) {
   /* ... */
}

/* In this source file, no buginf prototype in scope */
void buginf();
 
void h(void) {
  buginf("bug in function %s, line %d\n", __func__"h", __LINE__);  /* Violation */
  /* ... */
}

Compliant Solution

...

Code Block
bgColor#ccccff
langc
/* In another source file */
void buginf(const char *fmt, ...) {
   /* ... */
}

/* buginf prototype in scope in this source file */

void buginf(const char *fmt, ...);
 
void h(void) {
  buginf("bug in function %s, line %d\n", __func__"h", __LINE__); 
  /* ... */
}

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
langc
/* In another source file */
 
long f(long x) {
  return x < 0 ? -x : x;
}

/* In this source file, no f prototype in scope */
 
int g(int x) {
  return f(x);  /* Violation */
}

...

Code Block
bgColor#ccccff
langc
#include <fcntl.h>
 
void func(voidconst char *ms, mode_t perms) {
  /* ... */
  fd = open(ms, O_CREAT|O_EXCL|O_WRONLY|O_TRUNC, file_access_permissionsperms);
  if (fd == -1){
    /* Handle error */
  }
  /* ... */

}

Risk Assessment

Calling a function with incorrect arguments can result in unexpected or unintended program behavior.

...

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

Related Guidelines

...