简体   繁体   中英

C++ Access violation reading location 0xFFFFFFFFFFFFFFFF in dynamic array of vectors

The piece of code says something like: (Code is trying to fill an appearance array till 100) I fix size of array of vectors in arrayOne[0].numberOfThings because I know that it is the max number of items it can contain you can treat it like an known integer.

int max = 100;
int maxNThings = arrayOne[0].numberOfThings; //Integer that I know and I pickit as the max for dynamic array
    vector<Thing>* appearanceArrayOfNumThings;
    appearanceArrayOfNumThings= new vector<Thing>[maxNThings];
    for (int i = 0; i<max;i++){
        int currentNumberOfThings = arrayOne[i].numberOfThings;
        appearanceArrayOfNumThings[currentNumberOfThings ].push_back(arrayOne[i]);
    }

I am having

Access violation reading location 0xFFFFFFFFFFFFFFFF

inside the for statement, line appearanceArrayOfNumThings[currentNumberOfThings ].push_back(arrayOne[i]);

And I am thinking if it is because vector behaviour that I dont know.

Can you give me any clue or you seeing something I'm doing wrong?

First, you should use a debugger, you would have spotted the bug instantly.

Second, new vector<Thing>[maxNThings] is a bad idea. don't do that . Use std::vector<std::vector<Thing>> at least. A vector of struct containing a vector is clearer in my opinion.

Using a vector of vector, you can use .at() which would have told your error.


This code will always invoke undefined behaviour.

int maxNThings = arrayOne[0].numberOfThings;

Let's say for a moment that this number is 12 .

appearanceArrayOfNumThings = new vector<Thing>[maxNThings]; // 12

This create an array of 12 vectors. Indexable from 0 to 11 .

for (int i = 0; i < max ;i++){
    // ...
}

For the first iteration, i is equal to 0 . Let's continue.

// i == 0
int currentNumberOfThings = arrayOne[i].numberOfThings;

At this point, arrayOne[i] is the same value as arrayOne[0] , since i is equal to 0 . So currentNumberOfThings is equal to 12 , which is equal to maxNThings .

appearanceArrayOfNumThings[currentNumberOfThings ]

This access appearanceArrayOfNumThings[12] , which is out of bound since appearanceArrayOfNumThings is indexable from 0 to 11 . You enter UB land. Here's your bug.

It will always fail for any value of maxNThings .

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