对齐与否,这完全是错误的:
fpek = (float *)(&array[i]); // invalid for i>0, questionable for i==0
fprintf(stderr, "fpek = %lx ", (unsigned long) fpek);
*fpek = (float) i + 10;
由于array
最多有四个字符宽,即使您的系统 -float
是 4 个字节,您在分配时会立即寻址(可能未对齐)i
超出数组范围的数据字节i>0
。一旦您取消引用该指针,您要么会由于未对齐而导致总线错误,或者,如果您的体系结构没有对齐限制(float
并且大多数情况下),您将开始踩踏堆栈变量的赋值跟随。
为了突出作者可能试图克服的错误(对齐可能很重要)而不引入除此之外的未定义行为,请考虑以下内容:
#include <stdlib.h>
#include <stdio.h>
int main()
{
/* note: defined to hold enough bytes for *two* floats. */
float *fpek = NULL;
char array[2*sizeof(*fpek)];
int i;
/* fill with incrementing values */
for (i=0; i<sizeof(array)/sizeof(array[0]);++i)
array[i] = (i+1);
// now walk the array, one char at a time,
// casting the address of the current element
// to a float pointer and try to read/write it.
fprintf(stderr, "array = %p, size=%lu\n", array, sizeof(array));
for(i=0;i<sizeof(*fpek);++i)
{
fprintf(stderr,"i = %d, ", i);
fpek = (void*)(array+i);
fprintf(stderr, "fpek = %p, ", fpek);
*fpek = i+10;
fprintf(stderr, "*fpek = %.2f\n", *fpek);
}
return 0;
}
无论float
您的系统上的 a 有多宽/多窄,这都将起作用,而不会引入特定于走过 char 数组末尾的未定义行为。它很可能仍然会出现总线错误,但至少解决了超出数组下标的 UB。
在我的 Mac Air(英特尔 64 位 CPU)上运行它不会产生总线错误:
array = 0x7fff5fbff868, size=8
i = 0, fpek = 0x7fff5fbff868, *fpek = 10.00
i = 1, fpek = 0x7fff5fbff869, *fpek = 11.00
i = 2, fpek = 0x7fff5fbff86a, *fpek = 12.00
i = 3, fpek = 0x7fff5fbff86b, *fpek = 13.00
如您所见,我的平台对float
对齐并不是特别挑剔。您的结果可能(根据您之前的输出判断,可能会)有所不同。
注意:(void*)
演员阵容fpek = (void*)(array+i);
可能看起来很奇怪,但这是 C,所以我可以侥幸逃脱。我这样做的原因是为了让您演示其他浮点类型并查看它们是否有对齐限制。正如所写,您可以fpek
将函数顶部的声明更改为double
:
double *fpek = NULL;
然后重新运行程序。在我的系统上,这会产生:
array = 0x7fff5fbff860, size=16
i = 0, fpek = 0x7fff5fbff860, *fpek = 10.00
i = 1, fpek = 0x7fff5fbff861, *fpek = 11.00
i = 2, fpek = 0x7fff5fbff862, *fpek = 12.00
i = 3, fpek = 0x7fff5fbff863, *fpek = 13.00
i = 4, fpek = 0x7fff5fbff864, *fpek = 14.00
i = 5, fpek = 0x7fff5fbff865, *fpek = 15.00
i = 6, fpek = 0x7fff5fbff866, *fpek = 16.00
i = 7, fpek = 0x7fff5fbff867, *fpek = 17.00