Skip to main content

IAR Embedded Workbench for RX 5.20

CERT-EXP39-C_a

In this section:
Synopsis

Do not access a variable through a pointer of an incompatible type.

Enabled by default

Yes

Severity/Certainty

Medium/Low

mediumlow.png
Full description

Modifying a variable through a pointer of an incompatible type (other than unsigned char) can lead to unpredictable results.

Coding standards
CERT EXP39-C

Do not access a variable through a pointer of an incompatible type

Code examples

The following code example fails the check and will give a warning:

#include <stdlib.h>

struct gadget {
    int i;
    double d;
    char *p;
};

struct widget {
    char *q;
    int j;
    double e;
};

void func1fail(void) {
    struct gadget *gp;
    struct widget *wp;

    gp = (struct gadget *)malloc(sizeof(struct gadget));
    if (!gp) {
        /* Handle error */
    }
    /* ... Initialize gadget ... */
    wp = (struct widget *)realloc(gp, sizeof(struct widget));
    if (!wp) {
        free(gp);
        /* Handle error */
    }
    if (wp->j == 12) {
        /* ... */
    }
    /* ... */
    free(wp);
}

The following code example passes the check and will not give a warning about this issue:

#include <stdlib.h>

struct gadget {
    int i;
    double d;
    char *p;
};

struct widget {
    char *q;
    int j;
    double e;
};

void func1fail(void) {
    struct gadget *gp;
    struct widget *wp;

    gp = (struct gadget *)malloc(sizeof(struct gadget));
    if (!gp) {
        /* Handle error */
    }
    /* ... Initialize gadget ... */
    wp = (struct widget *)realloc(gp, sizeof(struct widget));
    if (!wp) {
        free(gp);
        /* Handle error */
    }
    memset(wp, 0, sizeof(struct widget));
    if (wp->j == 12) {
        /* ... */
    }
    /* ... */
    free(wp);
}