[英]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.