Main Content

ISO/IEC TS 17961 [intptrconv]

Converting a pointer to integer or integer to pointer

Description

Rule Definition

Converting a pointer to integer or integer to pointer.1

Polyspace Implementation

This checker checks for Conversion between pointers and integers.

Examples

expand all

Issue

The issue occurs when a conversion is performed between a pointer to object and an integer type.

Casts or implicit conversions from NULL or (void*)0 do not generate a warning.

Risk

Conversion between integers and pointers can cause errors or undefined behavior.

  • If an integer is cast to a pointer, the resulting pointer can be incorrectly aligned. The incorrect alignment causes undefined behavior.

  • If a pointer is cast to an integer, the resulting value can be outside the allowed range for the integer type.

Example - Casts between pointer and integer
#include <stdbool.h>

typedef unsigned char      uint8_t;
typedef          char      char_t;
typedef unsigned short     uint16_t;
typedef signed   int       int32_t;

typedef _Bool bool_t;
uint8_t *PORTA = (uint8_t *) 0x0002;            /* Non-compliant */

void foo(void) {

    char_t c = 1;
    char_t *pc = &c;                              /* Compliant */


    uint16_t ui16   = 7U;
    uint16_t *pui16 = &ui16;                      /* Compliant */
    pui16 = (uint16_t *) ui16;                    /* Non-compliant */


    uint16_t *p;
    int32_t addr = (int32_t) p;                  /* Non-compliant */
    bool_t b = (bool_t) p;                       /* Non-compliant */
    enum etag { A, B } e = ( enum etag ) p;      /* Non-compliant */
}

In this example, the rule is violated when:

  • The integer 0x0002 is cast to a pointer.

    If the integer defines an absolute address, it is more common to assign the address to a pointer in a header file. To avoid the assignment being flagged, you can then exclude headers files from coding rules checking. For more information, see Do not generate results for (-do-not-generate-results-for).

  • The pointer p is cast to integer types such as int32_t, bool_t or enum etag.

The rule is not violated when the address &ui16 is assigned to a pointer.

Check Information

Decidability: Undecidable

Version History

Introduced in R2019a


1 Extracts from the standard "ISO/IEC TS 17961 Technical Specification - 2013-11-15" are reproduced with the agreement of AFNOR. Only the original and complete text of the standard, as published by AFNOR Editions - accessible via the website www.boutique.afnor.org - has normative value.