C - 赋值后访问结构体属性会导致段错误

标签 c struct linked-list segmentation-fault

我有2个结构:wires和wireLLN(wires的链表节点)。这个想法是,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;
  }
}

感谢您的宝贵时间。

最佳答案

您遇到内存释放问题。你忘记了,一旦该功能停止运行,你的内存就会被删除。 这发生在 allocateWireFunction 中。

您可能想将其更改为:

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 的指针就停止分配内存。 然后您访问该内存(地址相同),但它不是允许您写入任何内容的内存。

关于C - 赋值后访问结构体属性会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49469185/

相关文章:

将 char 转换为 int 无效

c++ - 如何使用 fprintf 打印头文件中定义的结构成员值?

java - OutofMemory 链表添加错误

c - 在递归函数中使用 while

c - 如何动态分配(初始化)一个 pthread 数组?

arrays - 响应为空结构

c - 将结构体实例分配给 C 中的内部嵌套结构体

c - c中链表的升序

C4013 : undefined; assuming extern returning int

c - 帮助我理解 C 中这个简单的 malloc