程序在删除struct中的指针数组时崩溃

时间:2012-09-19 21:55:49

标签: c++ delete-operator

当删除命令出现时崩溃。它应该创建一个带有指向数组的结构,用随机数填充它们,然后释放内存。在删除命令之前工作正常,在没有for循环或布尔检查的情况下,它与我们崩溃。

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;
}

我正在使用MS Visual studio 2010。

3 个答案:

答案 0 :(得分:2)

罪魁祸首就是这条线:

data.ptrarray[i]++;

您正在更改指针,然后在修改后的指针上使用delete []。这不起作用:您必须使用与delete[]完全相同的指针new[]

尝试

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

因此您不必更改指针。

答案 1 :(得分:1)

你的问题在于:

data.ptrarray[i]++;

这是修改指针。当您尝试释放该修改后的指针时,它会崩溃。

您可以通过使用指针的副本来运行数组,或者使用j变量进行索引来解决此问题:

data.ptrarray[i][j]

答案 2 :(得分:1)

data.ptrarray[i]++;就是问题所在。

您正在递增对数据的引用,但在尝试删除之前不会将其重置为开头。