'How is this causing segmentation fault (short code) (C-language)
This is causing me segmentation fault, whenever i comment out breadthFirst = queue_enqueue(breadthFirst,n) or breadthFirst = queue_dequeue(breadthFirst) i no longer get seg fault but it obviously can't solve my task anymore.
I suppose it might be very hard to help me with this unless you know how the datatypes are implemented but i thought i might give it a shot and see if it is something obvious im missing.
bool find_path(graph *g,node *src, node *dest) {
queue *breadthFirst = queue_empty(NULL);
breadthFirst = queue_enqueue(breadthFirst,src);
while (!queue_is_empty(breadthFirst))` {
void *v = queue_front(breadthFirst);
g = graph_node_set_seen(g,v,1);
dlist *neighbours = graph_neighbours(g,v);
dlist_pos pos = dlist_first(neighbours);
while (!(dlist_is_end(neighbours,pos))) {
void *n = dlist_inspect(neighbours,pos);
if (graph_node_is_seen(g,n)) {
}
else {
breadthFirst = queue_enqueue(breadthFirst,n);
}
pos = dlist_next(neighbours,pos);
}
breadthFirst = queue_dequeue(breadthFirst);
}
}
struct queue {
list *elements;
};
queue *queue_empty(free_function free_func)
{
// Allocate the queue head.
queue *q=calloc(1, sizeof(*q));
// Create an empty list.
q->elements=list_empty(free_func);
return q;
}
queue *queue_enqueue(queue *q, void *v)
{
list_insert(q->elements, v, list_end(q->elements));
return q;
}
queue *queue_dequeue(queue *q)
{
list_remove(q->elements, list_first(q->elements));
return q;
}
void *queue_front(const queue *q)
{
return list_inspect(q->elements, list_first(q->elements));
}
As per request i added the queue implementation
Solution 1:[1]
Solved it! Thx for the tips tho, the information i presented was not enough for anyone to help me really. I did some debugging and found that i had misunderstood my implementations basically.
*n is a value in a struc
the *src i send in, is a node with a value and list
so it works fine on the first iteration, but then im trying to find a list from *n which is only just a void *value and is not a struc or a list. Then my program attempts to use first on whatever that list is and that caused segmentation fault.
The fix is to with the n value to use a function i have, to find the struct corresponding to that value.
Solution 2:[2]
Try modifying your queue_empty function like this :
queue *queue_empty(free_function free_func)
{
// Allocate the queue head.
queue *q=calloc(1, sizeof(queue));
// Create an empty list.
q->elements=list_empty(free_func);
return q;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabbeboo |
| Solution 2 | user438383 |
