如何将堆栈变量对齐到16字节边界



我有以下的局部变量(它将被存储在堆栈中):

struct test1 {
  int a;
  int b;
  char c;
};

如何将整数a的起始地址对齐到堆栈中的16byte边界?

我在一个自定义编写的MIPS ISA处理器上运行这个C代码。

这是一些非标准的对齐数据的方法。

struct test1 *pdata;
// here we assume data on stack is word aligned
pdata = alloca(sizeof(*pdata) + 14);
if (pdata & 0xF)
{
    pdata = (unsigned char*)pdata + 16 - (pdata & 0xF);
}

AFAIK在MIPS上,ISA C编译器在这种情况下强制对齐字边界,只需在结构中添加一个int(32位)。所以:

struct test1 {
   int a;       // 4 bytes
   int b;       // 4 bytes
   int foralign;// 4 bytes for 16 byte alignment
   char c;      // 1 byte but will be aligned 4 bytes
};

不幸的是,没有标准的方法来让对象像那样对齐。几乎总是有一些特定于编译器的技巧,例如GCC中的__attribute__,但您必须检查编译器的文档。

(当然也没有标准的使用来进行这种对齐,这就是为什么没有标准的方法来实现它。因此,您可能已经在使用扩展了,所以没有真正的危害。)

包含足够大的元素对象的union通常可以解决问题,但我认为MIPS cpu上最大的C元素对象是long longdouble,它们只有8个字节。

最新更新