Getting Access Violation error when creating an Edge via function

0

I am implementing a Graph ADT to use for a different program, and I was given these "insert" and "remove" functions that I needed to define. They are supposed to create an Edge (from the Edge struct) with two vertices and insert/remove it into a larger Graph. It runs fine when I create an instance of it in main, but when I try to call the insert or remove function it gives an error that says:

"First-chance exception at 0x00A56C84 in COMP222 -- Program3.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD".

Any ideas as to what I could be doing wrong here to cause this error? Again, the main problem is with insert/remove, but I posted the rest of it just in case.

    EDGE STRUCT

    struct Edge { //edge with vertices v1 and v2 
    int *vertex1;
    int *vertex2;
};


 GRAPH.H

#include "Graph.h"
#include <iostream>
Graph::Graph() {

    graphSize = 0;
};

Graph::Graph(const string& file) {

    text.open(file);
    while(!text.eof()) {
    char ch;
    text.get(ch);
    vertices.push_back(ch);
}
for(int i = 0;i < sizeof(vertices);i++) {
    static_cast<int>(vertices.at(i));
}
}
void Graph::insert(int v1,int v2) {
    Edge* newEdge = new Edge;

    *newEdge->vertex1 = v1;
    *newEdge->vertex2 = v2;

    v1 = vertices.at(0);
    v2 = vertices.at(2);

    graphSize += 2;
    };

    void Graph::remove(int v1,int v2) {
        Edge* delEdge = new Edge; //edge to be deleted

    *delEdge->vertex1 = v1;
    *delEdge->vertex2 = v2;

    delete delEdge->vertex1;
    delete delEdge->vertex2;

    graphSize -= 2;
    };

    ostream& operator <<(ostream& verts,const Graph& graph) {
    return verts;
    };



 MAIN FUNCTION -- problem seems to be with the test.insert and test.remove                       functions

#include "Graph.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main() {
    Graph test("Path to file...no problem here..."); //THIS WORKS FINE
    test.insert(2,3); //INSERT/REMOVE CAUSE THE ERROR
    test.remove(2,3);
    system("PAUSE");
    return 0;
}
c++
graph-theory
access-violation
abstract-data-type
asked on Stack Overflow Mar 26, 2014 by jordpw • edited Jan 13, 2020 by TylerH

1 Answer

1

The problem should with these two lines in the insert function:

*newEdge->vertex1 = v1;
*newEdge->vertex2 = v2;

vertex1 and vertex2 are uninitialized pointers, they are not pointing to valid locations in the memory and you are trying to write to those locations. I suspect you want vertex1 and vertex2 to simply be ints that hold vertex IDs.

A similarly write is attempted by your remove function. You should fix that too.

answered on Stack Overflow Mar 26, 2014 by DigitalEye

User contributions licensed under CC BY-SA 3.0