相关疑难解决方法(0)

取消引用空指针在sizeof操作中是否有效

我遇到了一段代码片段,对我来说应该会因为分段错误而崩溃,但它可以毫无障碍地工作.有问题的代码加上相关的数据结构如下(在上面找到相关的评论):

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]));
}
Run Code Online (Sandbox Code Playgroud)

为什么这样做?我收集了的sizeof字符*将解决对给定的体系结构指针的大小,但它不应该和好如初,同时取消引用NULL终场?

c sizeof null-pointer dereference

21
推荐指数
2
解决办法
4528
查看次数

标签 统计

c ×1

dereference ×1

null-pointer ×1

sizeof ×1