Pregunta

I recently ran into a crash in my code where I was unsure of how and why it was crashing and began using static analyizers, then I began using Intel Inspector XE 2013. I kept running into the same "Invalid memory access" in my code so I began to reduce my code to the smallest possible form to get it to reproduce, where I finally got to a point where it seems that there is an "Invalid memory access" in my code but only if my class has a destructor. The interesting this is that my "Invalid memory access" is happening on an address that is before the address it is trying to delete. The code that ended up "Invalid memory access" is not actually crashing my code, but I thought I would fix this potential issue encase it was having a snowball affect. My code in question is

class Group {
public:
    Group() {}
    ~Group() {} // When this line is not here, there will not be an "Invalid memory access"
};

int main() {
    Group** groups = new Group*[3];

    groups[0] = new Group();
    groups[1] = new Group();
    groups[2] = new Group();

    for(unsigned int i = 0; i < 3; ++i)
        delete [] groups[i];

    delete [] groups;

    return 0;
}

The "Invalid memory access" problem will be flagged on the first time it tries "delete [] group[i]" (so i will be equal to 0). The memory address that it is a flagged at is "0x003e30ec" where as group[0] is actually "0x003e30f0", which is 0x4 ahead. Whenever I run this test, it is consitantly at a difference of 0x4.

My question is, is there actually anything wrong with my code where I am reading or writing to memory improperly or is this person just a bad result from Intel Inspector XE 2013 (I am on Visual Studio 2012 Update 1)?

For those curious about my memory table with the example above, it is the following

groups == 0x003e30b8
groups[0] == 0x003e30f0
groups[1] == 0x003e3120
groups[2] == 0x003e3150
¿Fue útil?

Solución

for(unsigned int i = 0; i < 3; ++i)
        delete [] groups[i];

should be

for(unsigned int i = 0; i < 3; ++i)
        delete  groups[i];

new/delete, new [] /delete [] should always match. In your case just use std::vector<std::shared_ptr<Group> > groups; will be a better way.

where I finally got to a point where it seems that there is an "Invalid memory access" in my code but only if my class has a destructor.

using wrong delete[] is why your application is crashing, it has nothing to do with your destructor in this case, unless you have something hidden in your destructor but that will be another bug.

Otros consejos

I believe your problem is that you are using the array-style delete [], and you should be using just the regular delete. This is because each element in groups is a single Group object, not an array of them.

You do, however, need to use delete [] for the groups memory.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top