在C ++中删除时态数组

时间:2014-12-06 21:13:18

标签: c++ memory-management new-operator dynamic-memory-allocation delete-operator

我正在从一本书中学习动态记忆。据我所知,每次创建 new 变量时我们都需要删除它,并将指针设置为null,因此我们没有悬空指针。 / p>

我创建了一个程序,用于在[5]的动态数组中存储来自用户的值,每当用户添加更多内容时,我“展开”数组。在扩展时,我使用一个临时的新数组,当我尝试删除它时,给了我一个艰难的时间。为什么会这样?

size_t arraySize(5), index(0);

int inputvalue(0);
int *ptemporal(nullptr);

int *pvalues = new int[arraySize];

    for (;;){

        cout << "Enter value or 0 to end: ";
        cin >> inputvalue;  //enter value

        // exit loop if 0
        if (!inputvalue)  //if 0 break
            break;

        pvalues[index++] = inputvalue; //store values on pivalores

        if (index == arraySize){ //if limit reached create space

            cout << "Limit reached. Creating space...";

            arraySize += 5; //5 new memory blocks

            ptemporal = new int[arraySize]; //temporal value holder.

            for (size_t i = 0; i < arraySize - 5; i++)  //xfer values to temporal
                ptemporal[i] = pvalues[i];

                delete[] pvalues;       // delete values to  
                pvalues = ptemporal;  // assigning the same addres to pvalues.

                **delete[]  ptemporal; //causes a problem if I use the delete. if i comment the program works just fine.**

                ptemporal = nullptr;
        }


    }
return 0;
}

**这两个星号只是表明发生了问题。

2 个答案:

答案 0 :(得分:1)

您的问题是,在将指针复制到ptemporal后,您正在删除pvalues

pvalues = ptemporal; // assigning the same addres to pvalues.

delete[]  ptemporal; //causes a problem if I use the delete. if i commentt the program works just fine.**

换句话说,您删除刚刚创建的内存!因此,下次展开向量时,会尝试再次删除它,从而导致双重自由错误。这种错误是调试器帮助的地方,因此您可以在程序执行时观察变量值。

// start
ptemporal = nullptr;
pvalues   = /* location A */;


// first expansion
ptemporal = /* location B */;
// copy values from location A to B
delete[]    pvales;    /* location A */
pvalues   = ptemporal; /* location B! */
delete[]    ptemporal; /* location B */
ptemporal = nullptr;


// second expansion
ptemporal = /* location C */;
// copy values from location B to C, should segfault

// then you delete pvalues (aka location B) again!
// this results in a double free error
delete[]    pvales;    /* location B */

要解决此问题,只需删除第delete[] ptemporal;

即可

答案 1 :(得分:0)

您无需删除pTemporal。您已删除p值并希望将pTemporal移交给它。

delete [] pValues;
pValues = pTemporal;
pTemporal = NULL;