相关疑难解决方法(0)

指向无效内存时,sizeof(*ptr)是否未定义行为?

我们都知道解除引用空指针或指向未分配内存的指针会调用未定义的行为.

但是在传递给表达式时使用的规则是什么sizeof

例如:

int *ptr = 0;
int size = sizeof(*ptr);
Run Code Online (Sandbox Code Playgroud)

这也未定义吗?

c c++ language-lawyer

36
推荐指数
4
解决办法
1560
查看次数

取消引用空指针在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
查看次数

理解使用本地引用构建链表的逻辑

下面是使用本地参考逻辑创建链表的代码.无法理解for循环中的代码,尤其是第二行.(见// HERE)

有人可以详细说明这种逻辑是如何运作的.

void push(struct Node** head_ref, int new_data)
{
  struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
  newNode->data = new_data;

  newNode->next = *head_ref;
  *head_ref = newNode;

  return;
}


struct Node* buildWithLocalRef()
{
  int i=0;
  struct Node *head = NULL;
  struct Node **lastptrRef = &head;

  for(i=1;i<6;i++)
  {
    push(lastptrRef,i);
    lastptrRef = &((*lastptrRef)->next); // HERE
  }

  return head;
}

int main()
{
  struct Node* head;

  head = buildWithLocalRef();
  printList(head);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

c linked-list

1
推荐指数
1
解决办法
75
查看次数