c - 如何分配 16byte 内存对齐数据

标签 c memory sse icc

我正在尝试在一段代码上实现 SSE 矢量化,我需要我的一维数组与 16 字节内存对齐。但是,我尝试了几种方法来分配 16 字节内存对齐的数据,但它最终是 4 字节内存对齐的。

我必须使用英特尔 icc 编译器。 这是我正在测试的示例代码:

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

  void error(char *str)
  {
   printf("Error:%s\n",str);
   exit(-1);
  }

  int main()
  {
   int i;
   //float *A=NULL;
   float *A = (float*) memalign(16,20*sizeof(float));

   //align
   // if (posix_memalign((void **)&A, 16, 20*sizeof(void*)) != 0)
   //   error("Cannot align");

    for(i = 0; i < 20; i++)
       printf("&A[%d] = %p\n",i,&A[i]);

        free(A);

         return 0;
   }

这是我得到的输出:

 &A[0] = 0x11fe010
 &A[1] = 0x11fe014
 &A[2] = 0x11fe018
 &A[3] = 0x11fe01c
 &A[4] = 0x11fe020
 &A[5] = 0x11fe024
 &A[6] = 0x11fe028
 &A[7] = 0x11fe02c
 &A[8] = 0x11fe030
 &A[9] = 0x11fe034
 &A[10] = 0x11fe038
 &A[11] = 0x11fe03c
 &A[12] = 0x11fe040
 &A[13] = 0x11fe044
 &A[14] = 0x11fe048
 &A[15] = 0x11fe04c
 &A[16] = 0x11fe050
 &A[17] = 0x11fe054
 &A[18] = 0x11fe058
 &A[19] = 0x11fe05c

它每次都是 4 字节对齐的,我用过 memalign,posix memalign。由于我在 Linux 上工作,我不能使用 _mm_malloc 也不能使用 _aligned_malloc。 当我尝试使用 _aligned_attribute 时出现内存损坏错误(我认为仅适用于 gcc)。

谁能帮我在linux平台上为icc准确生成16字节内存对齐数据。

最佳答案

您分配的内存是 16 字节对齐的。见:
&A[0] = 0x11fe010
但是在float的数组中,每个元素都是4字节,所以第二个是4字节对齐的。

您可以使用具有 aligned 属性的结构数组,每个结构都包含一个 float :

struct x {
    float y;
} __attribute__((aligned(16)));
struct x *A = memalign(...);

关于c - 如何分配 16byte 内存对齐数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084468/

相关文章:

c++ - 使用 SIMD 查找表

c - 为什么我们不在 scanf 中使用 '&' 作为 char 数组

c - 应用程序请求与 Linux 内核响应的在线匹配

c++ - 内存布局问题

c - 为什么 sbrk() 不告诉我正在使用多少堆?

Java VM - 释放的内存是否返回到操作系统?

c - 计算c中两个矩阵之和时出错

python - 如何在 Python 中显式释放内存?

gcc - 如何使用 GCC 获得更好的矢量化?

intel - 是否可以创建大数组 AVX/SSE 值