سؤال

Following the topic How is an array aligned in C++ compared to a type contained? I made an experiment.

Here is the code:

#include<iostream>
using namespace std;

int main()
{
  const int N = 12;
  {
    float p1[N], p2[N];

    cout << p1 << " " << p2 << " " << p2 - p1 << endl;
  }

  {
    float* p1, *p2;

      // allocate memory
    p1 = new float[N];
    p2 = new float[N];

    cout << p1 << " " << p2 << " " << p2 - p1 << endl;
    delete[] p1;
    delete[] p2;
  }
}

According to the cited question and wiki I would expect that p1 and p2 would be sizeof(float) == 4 bytes aligned. But the result is:

0x7fff4fd2b410 0x7fff4fd2b440 12
0x7f8cc9c03bd0 0x7f8cc9c03c00 12

Same 12 distance between arrays for N = 9, 11 and 12. Distance (p2-p1) is 8 for N = 8. So it looks like float arrays is 16 bytes aligned. Why?

P.S. My processor is Intel Core i7

Compiler - g++ 4.6.3


It appears that putting arrays in a structure one can get 10 floats distance:

const int N = 10;

struct PP{
  float p1[N], p2[N];
};

int main() {

  PP pp;
  cout << pp.p1 << " " << pp.p2 << " " << pp.p2 - pp.p1 << endl;
}

0x7fff50139440 0x7fff50139468 10
هل كانت مفيدة؟

المحلول

Memory allocated by operator new always has suitable alignment for any object type, whatever the actual type being created. Additionally, it may also have a wider alignment (for example, alignment with a cache line) to improve performance.

If you replace your dynamic arrays with automatic ones (or better still, make them consecutive members of a class), then you may see narrower alignments. Or you may not; the exact details of how objects are aligned are up to the compiler, as long as it meets the minimum requirement for the type.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top