James P
James P

Reputation: 119

Program crashes on deleting array of pointers in struct

Crashes when the delete command comes around. It's supposed make a struct with pointers to arrays, fill them with random numbers, and then deallocate the memory. Works fine until the delete command, in which it crashes with our without the for loop or boolean check.

int main() {

    cout << "start" << endl;
    //Creating Struct
    struct 
    {
        int* ptrarray[10];
        bool boolarray[10];
    } data;

    //Initializing Random Generator
    srand ( time(NULL) );
    cout << "Initializing: ";

    //Allocating Memory and generating random numbers with for loops

    for (int i = 0; i < 10; i++)
    {   
        int counter = 0; //Counts numbers set   
        cout <<  i << " "; //Counting arrays initialized    
        data.ptrarray[i] = new int [12582912]; // Memory Allocation 

        for (int j = 0; j < 12582912; j++)//Number Generating
        {
            *data.ptrarray[i] = rand() % 899 + 100;
            data.ptrarray[i]++;
            counter++;
        }

        //Checking for failed initializations and declaring if success
        if (counter == 12582912)
        {
            data.boolarray[i] = true;
        }
        else
        {
            data.boolarray[i] = false;
        }
    }

    cout << endl;

    //This is where it always crashes.
    for (int i=0; i<10; i++)
    {
        if (data.boolarray[i] == true)
            delete[] data.ptrarray[i];
    }
    cout << endl;

    return 0;
}

I'm using MS Visual studio 2010.

Upvotes: 1

Views: 1107

Answers (3)

paxdiablo
paxdiablo

Reputation: 881423

Your problem lies with:

data.ptrarray[i]++;

This is modifying the pointer. When you then attempt to free that modified pointer, it crashes.

You can solve this by using a copy of the pointer to run through the array, or by indexing with thej variable as well:

data.ptrarray[i][j]

Upvotes: 1

user334856
user334856

Reputation:

data.ptrarray[i]++; is the problem.

You're incrementing your reference to the data, but then not resetting it to the start before trying to delete it.

Upvotes: 1

nneonneo
nneonneo

Reputation: 179422

The culprit is this line:

data.ptrarray[i]++;

You are changing the pointer, then using delete [] on the modified pointer. This will not work: you must use delete[] with the exact same pointer you got from new[].

Try

data.ptrarray[i][j] = rand() % 899 + 100;

instead so you don't have to change your pointer.

Upvotes: 2

Related Questions