【发布时间】:2013-11-16 02:55:50
【问题描述】:
我遇到了一段代码,对我来说应该因分段错误而崩溃,但它可以顺利运行。有问题的代码加上相关的数据结构如下(上面有相关的注释):
typedef struct {
double length;
unsigned char nPlaced;
unsigned char path[0];
}
RouteDefinition* Alloc_RouteDefinition()
{
// NB: The +nBags*sizeof.. trick "expands" the path[0] array in RouteDefinition
// to the path[nBags] array
RouteDefinition *def = NULL;
return (RouteDefinition*) malloc(sizeof(RouteDefinition) + nBags * sizeof(def->path[0]));
}
为什么会这样?我认为 sizeof 和 char* 将解析为给定架构上指针的大小,但它不应该在取消引用 NULL- 时崩溃和烧毁指针?
【问题讨论】:
-
约阿希姆的权利 (+1)。虽然
sizeof可能在编译器内部,但您通常可以通过查看标准库的offsetof实现以一种有趣且有形的形式观察到这种语言行为:它可能采用虚构对象的数据成员的地址通过强制转换一个 0/NULL 指针...这比sizeof更接近悬崖,但完全合法。 -
sizeof(def->path[0])定义为1,因此 return 语句折叠为更具可读性:return malloc(sizeof(RouteDefinition) + nBags);
标签: c sizeof dereference null-pointer