Versions Compared

Key

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

Using type definitions (typedef) can often improve code readability.  However, type definitions to pointer types can make it more difficult to write const-correct code because the const qualifier will be applied to the pointer type, not to the underlying declared type.

...

The following type definition improves readability at the expense of introducing a const-correctness issue.   In this example, the const qualifier applies to the typedef itself instead of applying to the underlying object type.   So Consequently, func does not take a pointer to a const struct obj, but is instead taking takes a const pointer to a struct obj.

Code Block
bgColor#FFcccc
langc
struct obj {
  int i;
  float f;
};
typedef struct obj *ObjectPtr;
 
void func(const ObjectPtr o) {
  /* Can actually modify o's contents, against expectations. */
}

...

This compliant solution makes use of type definitions , but does not declare a pointer type and so cannot be used in a const-incorrect manner.:

Code Block
bgColor#ccccff
langc
struct obj {
  int i;
  float f;
};
typedef struct obj Object;
 
void func(const Object *o) {
  /* Cannot modify o's contents. */
}

...

The Win32 SDK headers make use of type definitions for most of the types involved in Win32 APIs, but the following noncompliant solution demonstrates a const-correctness bug.:

Code Block
bgColor#FFcccc
langc
#include <Windows.h>
/* typedef char *LPSTR; */
 
void func(const LPSTR str) {
  /* Can mutate str's contents, against expectations. */
}

Compliant Solution (Windows)

The This compliant solution demonstrates a common naming convention found in the Win32 APIs, using the proper const type.:

Code Block
bgColor#ccccff
langc
#include <Windows.h>
/* typedef const char *LPCSTR; */
 
void func(LPCSTR str) {
  /* Cannot modify str's contents. */
}

...

Note that many structures in the Win32 API are declared with pointer type definitions , but not pointer-to const  type -const  type definitions (LPPOINT, LPSIZE, et al.).   In these cases, it is suggested to that you create your own type definition from the base structure type.

...

The following declaration of the signal() function is difficult to read and comprehend.:

Code Block
bgColor#FFcccc
langc
void (*signal(int, void (*)(int)))(int);

...

This compliant solution makes use of type definitions to specify the same type as in the noncompliant code example.:

Code Block
bgColor#ccccff
langc
typedef void SighandlerType(int signum);
extern SighandlerType *signal(
  int signum,
  SighandlerType *handler
);

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

 

LDRA tool suite

Include Page
LDRA_V
LDRA_V

299 S
381 S

Fully implemented

PRQA QA-C
Include Page
PRQA_V
PRQA_V
Secondary AnalysisanalysisFully implemented

Related Vulnerabilities

...

 

...