maxalign.c
来自「一套接口」· C语言 代码 · 共 63 行
C
63 行
#include <stdio.h>#include <stddef.h>#include <stdlib.h>#include <string.h>#include <assert.h>/*On most platforms, malloc returns pointers to blocks that arealigned on addresses that are multiples of the size of the largestbasic data type. Some CII functions use a union to determine thismultiple (cf. union align on p. 80). Alignments are less restrictiveon some platforms and, for these, MAXALIGN must be defined as thealignment required.This program attempts to determine the correct value for MAXALIGN, ifone is necessary, and echo the appropriate -D option. Unfortunately,the method used relies on the C compiler using the same alignments asmalloc, which is not required. malloc is the final authority: If itreturns addresses that are multiples of sizeof (union align), thenMAXALIGN is unnecessary; otherwise, MAXALIGN must provide thealignment. Incorrect values of MAXALIGN can cause crashes andassertion failures.*/union align { int i; long l; long *lp; void *p; void (*fp)(void); float f; double d; long double ld;};typedef void (*functp);#define yy \ xx(int,i);\ xx(long,l);\ xx(long *,lp);\ xx(void *,p);\ xx(functp,fp);\ xx(float,f);\ xx(double,d);\ xx(long double,ld);int main(int argc, char *argv[]) {#define xx(t,v) struct { char pad; t v; } v yy#undef xx unsigned max = 0;#define xx(t,v) if ((char *)&v.v - &v.pad > max) max = (char *)&v.v - &v.pad yy#undef yy if (argc > 1 && strcmp(argv[1], "-v") == 0) fprintf(stderr, "sizeof (union align) = %u\n", sizeof (union align)); assert(max); if (max != sizeof (union align)) printf("-DMAXALIGN=%u\n", max); return EXIT_SUCCESS;}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?