简体   繁体   中英

Access violation in c++

Beginner programmer here. I'm getting an access violation error in my directed graph program, and I'm wondering if anyone can tell me why.

Here's the trouble code (don't worry, it's not much). This code is from my main function. I've just read some info in from a file, parsed it, and am trying to insert it into a bucket using a function called InitialInsert.

//Store parsed file values
sourceCity = line[0]; 
destinationCity = line[1]; 
miles = stoi(line[2]); 
cost = stoi(line[3]); 

//Insert parsed values into Info bucket
graph.InitialInsert(sourceCity, destinationCity, miles, cost, size++); //Size is initialized to 0

This is the initial insert function.

//InitialInsert function
void Graph::InitialInsert(string source, string destination, int distance, int price, int index)
{
    InfoBuckets[index]->sourceCity = source; 
    InfoBuckets[index]->destinationCity = destination; 
    InfoBuckets[index]->miles = distance; 
    InfoBuckets[index]->cost = price; 
}

And this is from my header file.

static int const ARRAY_SIZE = 1000; 
struct InitialInfo
{
    string sourceCity; 
    string destinationCity;
    int miles; 
    int cost; 
};
InitialInfo* InfoBuckets[ARRAY_SIZE]; 

I'm getting the error "Access violation reading location 0xCCCCCCE4" when I hit the first line of my InitialInsert function. This is probably a silly problem, but can anyone help me out?

You are defined an ARRAY of 1000 pointers of InifitalInfo, but InitialInfo[0] never has been initialized.

Try this:

Array of Objects

InitialInfo InfoBuckets[ARRAY_SIZE];

...

void Graph::InitialInsert(string source, string destination, int distance, int price, int index)
{
   InfoBuckets[index].sourceCity = source; 
   InfoBuckets[index].destinationCity = destination; 
   InfoBuckets[index].miles = distance; 
   InfoBuckets[index].cost = price; 
}   

or

Array of pointers

InitialInfo *InfoBuckets[ARRAY_SIZE];

...

InfoBuckets[0] = new InitialInfo(); // You need create the object first before using

...

void Graph::InitialInsert(string source, string destination, int distance, int price, int index)
{
   InfoBuckets[index]->sourceCity = source; 
   InfoBuckets[index]->destinationCity = destination; 
   InfoBuckets[index]->miles = distance; 
   InfoBuckets[index]->cost = price; 
}

As @Roddy recomends, you must use smart pointers instead of new operators. You can read about in this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM