C - 分配后访问struct属性会导致分段错误

时间:2018-03-24 19:50:16

标签: c struct linked-list segmentation-fault

我有2个结构:wires和wireLLN(导线的链表节点)。我们的想法是findWire()函数在链表中查找具有与给定连线(wireName)同名的连线的节点。当添加第一条线时,这不会产生任何问题,因为头节点为空,因此创建了一个新节点,其中线作为节点的线路'属性。 addNode中的printf调用显示了这一点。但是,在第二轮findWire()上,尝试访问“线路”。头节点的属性导致分段错误。 (我已经评论过段错误出现在哪里)

typedef struct wires {
  bool value;
  char* name;
} Wire;

typedef struct wireLLN {
  Wire wire;
  struct wireLLN * nextNode;
} WireLLN;

//head of the linked list
WireLLN * headWire = NULL;

// adds a node to the linked list
void addNode(WireLLN* head, WireLLN* node){
  if (headWire == NULL){
    headWire = node;
        printf("Head node was null. Adding node with wire name: %s\n", headWire->wire.name); //this prints no problem
    }
  else if (head->nextNode == NULL)
    head->nextNode = node;
  else
    addNode(head->nextNode, node);
}

//finds if a wire with a given name already exists, if not returns null
Wire * findWire(char wireName[], WireLLN * head){
  if (headWire != NULL){
        puts("head wasnt null");
        printf("HEAD NODE ADDRESS: %s\n", head);
        printf("HEAD WIRE: %s\n", head->wire); //SEG FAULT HERE
    if (strcmp(head->wire.name, wireName) == 0){
            puts("1");
            return &head->wire;
        } else if (head->nextNode == NULL){
            puts("2");
            return NULL;
        } else {
            puts("3");
            return findWire(wireName, head->nextNode);
        }
  } else return NULL;
}


// assigns a wire to a gate if it exists, otherwise creates a new one then assigns it
Wire assignWire(char wireName[]){
  Wire * result = findWire(wireName, headWire);
  if (result == NULL){
    Wire wire = makeWire(wireName);
    WireLLN node;
    node.wire = wire;
    addNode(headWire, &node);
    return wire;
  } else {
    return *result;
  }
}

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

您有内存释放问题。 Yoiu忘记了一旦功能停止运行,你的记忆将被删除。 这发生在assignWireFunction。

您可能希望将其更改为:

Wire assignWire(char wireName[]){
  Wire * result = findWire(wireName, headWire);
  if (result == NULL){
    //to prevent the data being lost after the function returns
    WireLLN* node = (WireLLN*)malloc(sizeof(WireLLN));
    node->wire = makeWire(wireName);
    addNode(headWire, node);
    return node->wire;
  } else {
    return *result;
  }
}

你的NULL检查没有警告你的原因是,因为你给addNode的指针在函数返回后停止被分配内存。 然后你访问那个内存(地址是相同的),但它不是你被允许写任何东西的内存。