My professor wrote a code example for a graph and he wrote several functions. There is two functions in specific that called my attention. The constructor functiona and the Depth First Search... He first initializes the number of vertices on the constructor function by passing in a value. (5) and then in the Depth First Search he is trying to create a visited list to check which elements he has visited in the traversal. but the DFS function is got its own input (Which is 2). He dynamically allocates memory for the visited array but the memory allocated is the value that is passes which is 2. and then he uses a for loop to initialize all of them to false, but I don't understand why this is not an overflow. He run the program and it worked. (This is just two functions of the whole program) I am having trouble understanding why this is legal. Any help or explanation will help! Thanks!
class Graph
{
public:
int V;
// ... other code
}
Graph::Graph(int inV)
{
V = inV;
//...other code
}
void Graph::DFT(int inV)
{
bool * visited = newbool[inV]; // inV is 2
for(int i = 0; i < V; i++) // THIS IS THE PART I DON'T UNDERSTAND. V=5 WHY IS THERE NO MEMORY LEAK?
{
visited[i] = false;
}
}
int main()
{
Graph myGraph(5);
// ... Bunch of function calls that add edges
myGraph.DFT(2); // Depth First Traversal passing in the value of 2
}
You are correct. The code overflows it's bounds. You are simply lucky that the allocator returns a large enough block of memory that it doesn't trigger a bounds error exception -- that said, you could still be clobbering memory that belongs to something else you allocated. (It all depends on your compiler's implementation and other magic lucky charms.)
I recommend that you send your professor a polite email that says that you are confused by the indexing on the given lines, all without accusing him of screwing up. He'll fix it and tell the class about the repair, and maybe even take the time to talk a little about bounds errors.