Main Content

Typedef mismatch

Mismatch between typedef statements

Description

This checker is deactivated in a default Polyspace® as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).

This defect occurs when typedef statements lead to conflicting underlying types for one of these data types:

  • size_t

  • ssize_t

  • wchar_t

  • ptrdiff_t

Risk

If you change the underlying type of size_t, ssize_t, wchar_t, or ptrdiff_t, you have inconsistent definitions of the same type. Compilation units with different include paths can potentially use different-sized types causing conflicts in your program.

For example, say that you define a function in one compilation unit that redefines size_t as unsigned long. But in another compilation unit that uses the size_t definition from <stddef.h>, you use the same function as an extern declaration. Your program will encounter a mismatch between the function declaration and function definition.

Fix

Use consistent type definitions. For example:

  • Remove custom type definitions for these fundamental types. Only use system definitions.

  • Use the same size for all compilation units. Move your typedef to a shared header file.

Examples

expand all

file1.c:

#include <stddef.h>

void func1()
{
    size_t var = 0;
    /*... more code ... */
}

file2.c:

typedef unsigned char size_t;

void func2()
{
    size_t var = 0;
    /*... more code ... */
}

In this example, Polyspace flags the definition of size_t in file2.c as a defect. This definition is a typedef mismatch because another file in your project, file1.c, includes stddef.h, which defines size_t as unsigned long.

Correction — Use System Definition

One possible correction is to use the system definition of size_t in stddef.h to avoid conflicting type definitions.

file1.c:

#include <stddef.h>

void func1()
{
    size_t var = 0;
    /*... more code ... */
}

file2.c:

#include <stddef.h>

void func2()
{
    size_t var = 0;
    /*... more code ... */
}
Correction — Use Shared Header File

One possible correction is to use a shared header file to store your type definition that gets included in both files.

types.h:

typedef unsigned char size_t;

file1.c:

#include "types.h"

void func1()
{
    size_t var = 0;
    /*... more code ... */
}

file2.c:

#include "types.h"

void func2()
{
    size_t var = 0;
    /*... more code ... */
}

Result Information

Group: Programming
Language: C | C++
Default: On
Command-Line Syntax: TYPEDEF_MISMATCH
Impact: High

Version History

Introduced in R2016b