Safeguard
Application Security•

CWE-588: Accessing a Field Through a Non-Structure Pointer Cast

Cast a plain variable to a struct and write to its fields, and you corrupt whatever sits next to it in memory. How CWE-588 happens and how to avoid it.

Safeguard Security Team
3 min read

CWE-588 covers a simple but dangerous move in C and C++: casting a non-structure type to a structure type, then reading or writing a field of it. The compiler allows the cast. The memory behind it was never shaped like that structure.

How it happens

The pattern usually comes from convenience. A buffer, a scalar, or a union member is reinterpreted as a struct so the code can use named fields.

/* Vulnerable pattern */
struct header { int type; int length; char name[32]; };

char flag = 0;
struct header *h = (struct header *)&flag;
h->length = 4096;   /* writes well past the one byte of flag */

Only one byte was ever reserved, yet the field assignment lands at an offset beyond it, on top of neighbouring variables.

The one example CVE in MITRE's record fits this shape. CVE-2021-3510 is listed as a JSON decoder that accessed a C union using an invalid offset to an object.

What an attacker gains

MITRE lists two consequences.

  • Integrity. Adjacent variables in memory may be corrupted by assignments performed on fields after the cast.
  • Availability. Execution may end due to a memory access error.

Whether corruption becomes something worse depends on what the neighbouring memory holds, which is why this class deserves attention in parsers that handle untrusted input.

How to find it

Static analysis (SAST) can find some instances by tracking data flow and types. The mitigation guidance adds a simple manual check: review type casting operations to find places where incompatible types are cast.

A practical review habit is to grep for casts to struct pointers and ask, for each one, what object really lives at that address and how big it is.

How to fix it

  • Choose a language that is not susceptible to these issues where the requirements allow it.
  • Review every cast between incompatible types.
  • When you must interpret bytes as a structure, check the size first and copy into a properly typed object instead of aliasing.
/* Safer: verify size, then copy into a real struct */
struct header h;
if (len < sizeof h) { return -1; }
memcpy(&h, buf, sizeof h);

For unions, keep a tag that records which member is active, and only read that member.

Quick check

Why is a field write after the cast dangerous? The field sits at an offset that may be outside the original object, so the write corrupts adjacent variables.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.