Safeguard
Application Security•

CWE-188 Reliance on Data/Memory Layout: Why Assumptions Break

Code that assumes how structs, padding or protocol fields are arranged breaks when platforms or protocol versions change. CWE-188 and how to test for it.

Safeguard Security Team
3 min read

CWE-188, Reliance on Data/Memory Layout, happens when a product makes invalid assumptions about how protocol data or memory is organised at a lower level. It mainly concerns C and C++ code, and protocol implementations in any language.

How it happens

MITRE explains the problem with a simple picture. Some architectures place local variables A and B next to each other with A on top. Others put B on top. Others add padding to keep each variable aligned to a word size, and the padding differs. Code that assumes one arrangement behaves differently, and sometimes dangerously, on another.

Protocols have the same trap. Implementations often compute an offset relative to another field to pick out a piece of data. A new protocol version can add a corner case that changes the layout in an unusual way. The code then reads an unintended field, treating data of one type as data of another.

// Fragile: assumes no padding and a fixed field order in memory
struct header { char type; int length; };
char buf[5];
memcpy(buf, &hdr, 5);        // padding makes sizeof(struct header) larger than 5

// Better: serialise each field explicitly
buf[0] = hdr.type;
memcpy(buf + 1, &len_be, 4); // len_be converted to a defined byte order

What an attacker gains

MITRE lists integrity and confidentiality impact: unintended modification or exposure of sensitive memory.

How to find it

MITRE's listed methods:

  • Fuzzing, which generates many diverse inputs and can reveal crashes and memory corruption.
  • Automated dynamic analysis with compiler inserted runtime checks, such as AddressSanitizer for C and C++. MITRE notes crafted inputs are necessary to reach the code that has the error.

Also build and test on every platform and architecture you ship to, since layout bugs hide on the one you develop on.

How to fix it

The record gives no mitigations, so these are general steps.

  1. Never rely on struct layout for wire formats or files. Read and write each field explicitly.
  2. Use fixed width types and defined byte order for serialised data.
  3. Validate field offsets and lengths against the actual buffer size on every read.
  4. Run tests with sanitizers in CI.

Quick check

Why is this hard to catch on your own machine? The layout is stable on one platform and compiler. The assumption only fails on a different architecture or protocol version.

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.