Versions Compared

Key

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

...

There may be unnamed padding at the end of within a structure or unionobject, but not at its beginning.

This is often referred to as structure padding. Structure members are arranged in memory as they are declared in the program text. Padding is added to the structure to ensure the structure is properly aligned in memory.

Non-Compliant Code Example

In the The example below, is inspired by Dowd, assuming that sizeof(buf) the size of struct buffer is equal to sizeof(size_t) + (sizeof(char) * 50), which would equal 54 (assuming sizeof(size_t) is 4 bytes) equals 54 may be incorrect. The sizeof(buf) size of struct buffer may actually evaluate to be a larger value due to structure padding.

Code Block
struct buffer {
    size_t size;
    char buffer[50];
};

...

void func(struct buffer *buf_ptr) {

  struct buffer *buf_cpy = malloc((sizeof(size_t)+(sizeof(char)*50)));

  if (buf_ptrcpy == NULL) {
    /* ThisHandle may not be true malloc() error */
  }
  
  ...

  memcpy(buf_cpy,buf, sizeof(struct buffer)); /* May result in a small buffer overflow */
}