【发布时间】:2012-09-10 15:03:08
【问题描述】:
通常在 C 中访问超出其末尾的数组是未定义的行为。例如:
int foo[1];
foo[5] = 1; //Undefined behavior
如果我知道数组末尾之后的内存区域已被分配,使用 malloc 还是在堆栈上,它仍然是未定义的行为吗?这是一个例子:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int len;
int data[1];
} MyStruct;
int main(void)
{
MyStruct *foo = malloc(sizeof(MyStruct) + sizeof(int) * 10);
foo->data[5] = 1;
}
我已经在几个地方看到过这个模式用于制作可变长度的结构,并且它似乎在实践中有效。是技术上未定义的行为吗?
【问题讨论】:
-
Raymond Chen 在 Windows 中有一篇关于此模式的文章,标题为 Why do some structures end with an array of size 1?
标签: c undefined-behavior