【发布时间】: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->wire是structure而不是char buffer,你不能在上面做%s。
标签: c struct linked-list segmentation-fault