Muhammad Owais
Muhammad Owais

Reputation: 67

bad pointer error in c++ code

Here is the code for adding vertex to a graph:

void myGraph::addVertex(const string &newVertex)
{
    if (getIndex(newVertex) != -1)
    {
        std::cout << ("addVertex: ");
        std::cout << newVertex;
        std::cout << (" failed -- vertex already exists.") << std::endl;
        return;
    }

    // if array of vertices is full, we need to expand it and 
    // also expand Edges
    if (sizeof(Vertices)/sizeof(Vertices[0])==numVertices)
    {
        Vertices = resize(Vertices, 2*numVertices + 1);
        Edges = resize(Edges, 2*numVertices + 1);
    }

    Vertices[numVertices++] = newVertex;

}

and here is the code for resizing of Vertices array:

string *myGraph::resize(string array1[], int newSize)
{

    // make array of size equal to new size
    string *temp = new string [newSize];
    int smallerSize = newSize;
    // if the size of input array is less than the new size then smaller size will be that of input array
    if (sizeof(array1)/sizeof(array1[0]) < smallerSize)
    {
        smallerSize = sizeof(array1) / sizeof(array1[0]);
    }
    // loop till smaller size and copy the content of input array to newly created array
    for (int i = 0; i < smallerSize; i++)
    {
        temp[i] = array1[i];
    }

    return temp;
}

When I debug this code, it adds only 1 vertice, i.e. numVertices=1 and on next step it says in Vertices[numVertices++]

Upvotes: 0

Views: 432

Answers (2)

marcinj
marcinj

Reputation: 50036

You can fix it by passing old array size to resize:

string *myGraph::resize(string array1[], int array1Size, int newSize)

then:

if (array1Size < smallerSize) {
   smallerSize = array1Size ;
}

as Katie explains, sizeof(array1) in your code is not the size of the actual array, you should rather use string* array1 to make clear that it is pointer to allocated memory on heap

Upvotes: 1

Katie
Katie

Reputation: 1270

sizeof is giving the size of the pointer to the data in your array, not the total size of the array. It depends on your platform, but it is very likely that sizeof(string*)/sizeof(string) (equivalent to your size calculation) is always going to return 1. You should probably be using something like std::vector or std::list for this, the right choice depends on how exactly you will be using it. These standard container classes will handle allocating memory and resizing for you, so you don't have to worry about it.

Upvotes: 2

Related Questions