如果分配了该区域,则访问超出其末尾的数组是否是未定义的行为? [英] Is it undefined behaviour to access an array beyond its end, if that area is allocated?

查看:30
本文介绍了如果分配了该区域,则访问超出其末尾的数组是否是未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
是struct hack"吗?技术上未定义的行为?

通常在数组末尾访问数组是 C 中未定义的行为.例如:

Normally accessing an array beyond its end is undefined behavior in C. For example:

int foo[1];
foo[5] = 1; //Undefined behavior

如果我知道数组末尾之后的内存区域已经分配,​​使用 malloc 还是在堆栈上,它仍然是未定义的行为吗?下面是一个例子:

Is it still undefined behavior if I know that the memory area after the end of the array has been allocated, with malloc or on the stack? Here is an example:

#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;
}

我已经看到在几个地方使用这个模式来制作可变长度的结构体,它似乎在实践中有效.这是技术上未定义的行为吗?

I have seen this patten used in several places to make a variable length struct, and it seems to work in practice. Is it technically undefined behavior?

推荐答案

你所描述的被亲切地称为 结构黑客".不清楚它是否完全可以,但它曾经并且被广泛使用.

What you are describing is affectionately called "the struct hack". It's not clear if it's completely okay, but it was and is widely used.

最近(C99),它已经开始被灵活数组成员"取代,你可以在其中放置一个int data[]; 字段,如果它是结构中的最后一个字段.

As of late (C99), it has started to be replaced by the "flexible array member", where you're allowed to put an int data[]; field if it's the last field in the struct.

这篇关于如果分配了该区域,则访问超出其末尾的数组是否是未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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