堆栈变量是否由GCC __attribute __((aligned(x)))对齐? [英] Are stack variables aligned by the GCC __attribute__((aligned(x)))?

查看:406
本文介绍了堆栈变量是否由GCC __attribute __((aligned(x)))对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

i have the following code:

#include <stdio.h>

int
main(void)
{
        float a[4] __attribute__((aligned(0x1000))) = {1.0, 2.0, 3.0, 4.0};
        printf("%p %p %p %p\n", &a[0], &a[1], &a[2], &a[3]);
}

我有以下输出:

0x7fffbfcd2da0 0x7fffbfcd2da4 0x7fffbfcd2da8 0x7fffbfcd2dac

为什么地址 a [0] 不是 0x1000

究竟是什么 __属性__((aligned(x)))呢?我误解了这个解释?

What exactly __attribute__((aligned(x))) does? I misunderstood this explanation?

我使用的是gcc 4.1.2。

I'm using gcc 4.1.2.

推荐答案

I相信问题是你的数组在栈中。因为当函数启动时堆栈指针可能是任何东西,所以没有办法对齐数组而不分配比需要更多的东西并调整它。如果将数组移出函数并将其转换为全局变量,它应该可以工作。你可以做的另一件事是保持它作为一个局部变量(这是一件非常好的事情),但使它成为 static 。这将防止它被存储在堆栈上。请注意,这两种方式都不是线程安全的或递归安全的,因为只有一个数组副本。

I believe the problem is that your array is on the stack. Because the stack pointer could be anything when the function starts, there is no way to align the array without allocating a lot more than you need and adjusting it. If you move the array out of the function and into a global variable, it should work. The other thing you could do is keep it as a local variable (which is a very good thing), but make it static. This will prevent it from being stored on the stack. Beware that both of these ways are not thread-safe or recursion-safe, since there will be only one copy of the array.

使用以下代码:

#include <stdio.h>

float a[4] __attribute__((aligned(0x1000))) = {1.0, 2.0, 3.0, 4.0};

int
main(void)
{
        printf("%p %p %p %p\n", &a[0], &a[1], &a[2], &a[3]);
}

我得到这个:

I get this:

0x804c000 0x804c004 0x804c008 0x804c00c

这是预期的。用你原来的代码,我只是得到像你一样的随机值。

which is what is expected. With your original code, I just get random values like you did.

这篇关于堆栈变量是否由GCC __attribute __((aligned(x)))对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆