Bug 24944 - Size of type not multiple of its alignment.
Summary: Size of type not multiple of its alignment.
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: middle-end (show other bugs)
Version: 4.0.2
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
Depends on:
Reported: 2005-11-19 18:03 UTC by Neil Turton
Modified: 2012-01-11 14:58 UTC (History)
1 user (show)

See Also:
Host: i486-linux-gnu
Target: i486-linux-gnu
Build: i486-linux-gnu
Known to work:
Known to fail:
Last reconfirmed: 2012-01-11 00:00:00


Note You need to log in before you can comment on or make changes to this bug.
Description Neil Turton 2005-11-19 18:03:40 UTC
This topic was discussed in the following thread, but nothing seems to have happened.  I couldn't find a bug report.

The test case below demonstrates some problems with arrays of aligned types.  Packing the aligned type in a structure fixes the problems.

FAIL: sizeof(foo_aligned)!=8  {7!=8}
FAIL: sizeof(foo_aligned_array)!=100*8  {700!=800}
FAIL: p2-p1!=3*8  {18!=24}

It appears that getting the address of x[3] rounds the size down to the alignment, so this should be fixed by ensuring that the size is a multiple of the alignment.

#include <stdio.h>
#include <stdlib.h>

typedef char foo[7];
typedef foo foo_aligned __attribute__((aligned(2)));
typedef struct { foo_aligned c; } foo_aligned_struct;
typedef foo_aligned foo_aligned_array[100];
typedef foo_aligned_struct foo_aligned_struct_array[100];

int result = 0;

void fail(const char *as, int a, const char *bs, int b)
  fprintf(stderr, "FAIL: %s!=%s  {%d!=%d}\n", as, bs, a, b);
  result = 1;

#define expect(A,B) \
  do { if((A)!=(B)) fail(#A, A, #B, B); } while(0)

int main()
  foo_aligned_array x;
  foo_aligned_struct_array y;
  char *p1, *p2;

  expect(sizeof(foo_aligned), 8);
  expect(sizeof(foo_aligned_struct), 8);
  expect(sizeof(foo_aligned_array), 100*8);
  expect(sizeof(foo_aligned_struct_array), 100*8);
  p1 = (char*)&(x[0]);
  p2 = (char*)&(x[3]);
  expect(p2-p1, 3*8);
  p1 = (char*)&(y[0]);
  p2 = (char*)&(y[3]);
  expect(p2-p1, 3*8);
  return result;
Comment 1 Richard Biener 2012-01-11 14:58:06 UTC

There is no good way to specify the alignment of an array (either to more
nor less of its natural alignment).