Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Accounting for structure padding prevents these types of errors.:

Code Block
bgColor#ccccff
langc
enum { buffer_size = 50 };

struct buffer {
  size_t size;
  char bufferC[buffer_size];
} buff;

/* ... */

void func(const struct buffer *buf) {

  struct buffer *buf_cpy = 
    (struct buffer *)malloc(sizeof(struct buffer));

  if (buf_cpy == NULL) {
    /* Handle malloc() error */
  }

  /* ... */

  memcpy(buf_cpy, buf, sizeof(struct buffer));

  /* ... */

  free(buf_cpy);
}

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Bibliography

[Dowd 2006]Chapter 6, "C Language Issues" ("Structure Padding," pp. 284–287)
[ISO/IEC 9899:2011]Section 6.7.2.1, "Structure and Union Specifiers"
[Sloss 2004]Section 5.7, "Structure Arrangement"

...