【问题标题】:C - Accessing struct attribute after assignment causes Segmentation FaultC - 分配后访问结构属性导致分段错误
【发布时间】:2018-03-24 19:50:15
【问题描述】:

我有 2 个结构:wire 和wireLLN(用于wire 的链表节点)。这个想法是 findWire() 函数在链接列表中查找具有与给定连线 (wireName) 同名的连线的节点。添加第一条线时,这运行没有问题,因为头节点为空,因此创建了一个新节点,该线作为节点的“线”属性。 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;
  }
}

感谢您的宝贵时间。

【问题讨论】:

  • 您尝试将指向结构的指针打印为 C 字符串,然后将结构的指针打印为 C 字符串。预计会出现段错误。
  • head->wirestructure 而不是char buffer,你不能在上面做%s

标签: c struct linked-list segmentation-fault


【解决方案1】:

您有内存释放问题。你忘了,一旦功能停止运行,你的记忆就会被删除。 这发生在 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 的指针在函数返回后停止分配内存。 然后您访问该内存(地址相同),但它不是您被允许写入任何内容的内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2016-10-22
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多