繁体   English   中英

在C ++中删除时间数组

[英]Deleting a temporal Array in C++

我正在从一本书中处理动态内存。 据我了解,每次创建变量时,我们都需要将其删除,并将指针设置为null,因此我们没有悬挂的指针

我创建了一个程序,将来自用户的值存储在动态数组[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;
}

**这两个星号只是用来说明问题是否发生。

您的问题是,您将指针复制到pvalues之后就删除了ptemporal

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;

您不需要删除pTemporal。 您已经删除了pValues,并希望将pTemporal移交给它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM