Main Content

CWE Rule 588

Attempt to Access Child of a Non-structure Pointer

Since R2026a

Description

Casting a non-structure type to a structure type and accessing a field can lead to memory access errors or data corruption

Polyspace Implementation

Polyspace® checks for the issue Accessing child of nonstructure pointer

Examples

expand all

Issue

This issue occurs when these events occurs in succession:

  1. A pointer to a nonstructure type is cast to a pointer to structure type.

  2. A field of the structure is accessed using the resulting pointer.

  3. The value of the field is then assigned to a variable.

Risk

Accessing a field through a miscast structure pointer can cause out-of-bounds memory access or undefined behavior. The program may read or write unintended memory, leading to crashes, data corruption, or security vulnerabilities.

Fix
  • Avoid casting unrelated pointer types, such as function pointers or integer addresses, to pointers to structure types and then access fields of the structure.

  • When dereferencing a structure pointer, verify that it points to a structure type.

Example

In this example, a function pointer is cast to a structure pointer and a field is accessed.

#include <stdio.h>

struct Foo {
    int i;
};

int some_function(void) { return 0; }

int main(void)
{
    struct Foo *fp = (struct Foo *)some_function; // Noncompliant: casting function pointer to structure pointer
    fp->i = 42;                                    
    printf("%d\n", fp->i);                         
    return 0;
}
Correction

The corrected code defines a valid pointer to a Foo structure instance before accessing its field.

#include <stdio.h>
#include <stdlib.h>

struct Foo {
    int i;
};

int main(void)
{
    struct Foo *fp = malloc(sizeof *fp);
    if (fp == NULL) {
        return 1;
    }

    fp->i = 42;           // Compliant: accessing field of a properly allocated struct
    printf("%d\n", fp->i); 

    free(fp);
    return 0;
}

Check Information

Category: Others
PQL Name: std.cwe_native.R588

Version History

Introduced in R2026a