c++ - SIGSEGV error with BFS Algorithm -
i have bfs algorithm error. have tried debug gdb
don't understand why this.
can tell me why sigsegv
error code below. depend on compiler use how pointers addressed? there invalid pointer error in code
#include<iostream> #include<stdlib.h> #define true 1 #define false 0 using namespace std; const int max = 8; struct node { int data; node *next; }; class graph { private: int visited[max]; int q[8]; int front, rear; public: graph(); void bfs(int v, node **p); node *getnode_write(int val); static void addqueue(int *a, int vertex, int *f, int *r); static int deletequeue(int *q, int *f, int *r); static int isempty(int *f); void del(node *n); }; // initialize data memeber graph::graph() { for(int = 0; < max; i++) visited[i] = false; front = rear = -1; } // function implements breadth first search (bfs) algorithm void graph::bfs(int v, node **p) { node *u; visited[v-1] = true; cout<<v<<"\t"; addqueue(q, v, &front, &rear); while(isempty(&front) == false) { v = deletequeue(q, &front, &rear); u = *(p+v-1); while(u != null) { if(visited[u->data-1] == false) { addqueue(q, u->data, &front, & rear); visited[u->data-1] == true; cout<<u->data<<"\t"; } u = u->next; } } } // creates node node *graph::getnode_write(int val) { node *newnode = new node; newnode->data = val; return newnode; } //adds node queue void graph::addqueue(int *a, int vertex, int *f, int *r) { if(*r == max -1) { cout<<"\nqueue overflow."; exit(0); } (*r)++; a[*r] = vertex; if(*f == -1) *r = 0; } // deletes node queue int graph::deletequeue(int *a, int *f, int *r) { int data; if(*f == -1) { cout<<"\nqueue underflow"; exit(0); } data = a[*f]; if(*f == *r) *f = *r = -1; else (*f)++; return data; } // checks if queque empty int graph::isempty(int *f) { if(*f == -1) return true; return false; } // deallocate memory void graph::del(node *n) { node *temp; while(n != null) { temp = n->next; delete n; n = temp; } } int main() { node *arr[max]; node *v1,*v2,*v3,*v4; graph g; v1 = g.getnode_write(2); arr[0] = v1; v1->next = v2 = g.getnode_write(3); v2->next = null; v1 = g.getnode_write(1); arr[1] = v1; v1->next = v2 = g.getnode_write(4); v2->next = v3 = g.getnode_write(5); v3->next = null; cout<<endl; g.bfs(1,arr); for(int = 0; i<max; i++) g.del(arr[i]); }
there uninitialized array arr
in stack frame of main
. arr[0]
, arr[1]
become initialized. @ end of main iterated on whole array , delete
called in graph::del(node *n)
on garbage value.
Comments
Post a Comment