簡體   English   中英

C-分配后訪問結構屬性導致分段錯誤

[英]C - Accessing struct attribute after assignment causes Segmentation Fault

我有2個結構:wire和wireLLN(電線的鏈表節點)。 這個想法是,findWire()函數通過鏈接列表查找具有與給定電線(wireName)同名的電線的節點。 添加第一個導線時,這沒有問題,因為頭節點為空,因此將使用導線作為節點的“ wire”屬性創建一個新節點。 addNode中的printf調用顯示了這一點。 但是,在第二次運行findWire()時,嘗試訪問頭節點的'wire'屬性會導致分段錯誤。 (我已注釋了段錯誤在代碼中出現的位置)

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;
  }
}

謝謝你的時間。

您有內存釋放問題。 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的指針一旦函數返回就停止分配內存。 然后訪問該內存(地址相同),但不訪問允許您寫入任何內容的內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM