...
Accounting for structure padding prevents these types of errors.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
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
| CERT C++ Secure Coding Standard | EXP03-CPP. Do not assume the size of a class or struct is the sum of the sizes of its members |
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" |
...