[英]How can I align a string literal to an address which is multiple of 4?
我想確保給定的字符串文字最終到達的地址是2的倍數,甚至更好的是4。
有什么方法可以做到這一點,最好不使用任何編譯器特定的擴展? 還是不可能?
我想這樣做,因此字符串地址的最低位是0,可以用作標簽位。
您可以使用C11(但不能使用C99)執行此操作。 對於靜態分配的緩沖區,可以使用alignas
來執行此操作:
#include <stdio.h>
#include <stdalign.h>
alignas(4) char str[] = "this is aligned to at least 4 bytes";
int main() {
char a;
alignas(4) char str2[] = "and again";
printf("%p\n", &a);
printf("%p\n", str);
printf("%p\n", str2);
}
上面的技巧是實際上使用字符串文字來初始化相同大小的char數組,這使您可以在類型中使用alignas
。
對於動態分配的對象,請使用aligned_alloc(size_t alignment, size_t size)
而不是malloc
。
還有其他一些較舊的非標准方法也可以與GCC / Clang / Intel編譯器一起使用,因此,如果您始終沒有C11,則可以通過一些額外的預處理工作來完成,例如:
#if __STDC_VERSION__ >= 201112L
# include <stdalign.h>
# define force_align(x) alignas(x)
#elif defined __GNUC__
# define force_align(x) __attribute__((aligned(x)))
#elif defined __MSC_VER
# define force_align(x) __declspec(align(x))
#else
# error Who are you?
#endif
force_align(128) int x; // Note: maybe your linker doesn't actually support 128 anyway!
例如,在C99中,您可以使用聯合來執行此操作
#define ALIGNED_STR_UNION(N, S) const union { char s[sizeof S]; int align; } N = { S }
ALIGNED_STR_UNION(sssu, "XYZABC");
根據需要調整int
類型。
這樣, sssu.s
指的是字符。
該.s
可避免像
#define ALIGNED_STR(S) ((const union { char s[sizeof S]; int align; }){ S }.s)
const char *sss = ALIGNED_STR("XYZABC");
但是,此版本浪費了指針的空間(包括位置無關代碼的相對重定位),並且不允許在函數中聲明靜態文字。
最好使用非標准的對齊方式屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.