何时在声明结构时使用new

时间:2015-11-09 14:48:17

标签: c++

您何时使用new在c ++中声明结构?这些链接不使用newhttp://www.cplusplus.com/doc/tutorial/structures/ http://www.tutorialspoint.com/cplusplus/cpp_data_structures.htm

这个链接也与我的问题类似,但没有回答为什么分段错误: when to use new in C++?

struct Node {
  int data;
  struct Node *next;
}
//Add node to end of singly linked list
Node* Insert(Node *head,int data)
{
  //create node
  Node *temp = new Node;     //  *why not:   Node *temp;  :Causes segfault*
  temp->data = data;
  temp->next = '\0';
  //check for empty linked list
  if(head == '\0') {
      head = temp;
  }
  //add to end
  else {
      Node *curr = head;
      while(curr->next != '\0') {
          curr = curr->next;
      }
      curr->next = temp;
  }
  return head;

}

1 个答案:

答案 0 :(得分:4)

每当需要为数据结构分配内存(通常在堆上)时,都使用new。现在关于segfault:如果你只保留行

Node *temp; // no more = new Node; here

然后你尝试访问它指向的更远的内存

temp->data = data;
temp->next = '\0';

但是没有分配内存,所以你会写入一些碰巧存储在temp中的垃圾内存地址。你必须记住Node* temp;只是声明指向struct的指针,不初始化它也不为它分配内存

在您的情况下,您可能会认为Node data;会这样做。但是,问题是对象data现在很可能存储在堆栈中,并且它将在函数出口处释放,因此您最终会得到悬空指针。这就是你需要使用new的原因,因为动态分配的对象不限于本地范围。

相关问题