0

很久以前我在读一本书,并告诉我如何为指针分配和释放内存的模式。出于某种原因,它现在不适用于我的项目和我之前的项目。直到现在我才决定解决这个分配问题。所以这是有问题的代码:

    // Encrypting or Decrypting Mode
    bool ModeSelected(false);                   // stores the result if the user had selected a valid mode
    bool Mode(ENCRYPT);                         // saves the Mode if Encrypt or Decrypt

    while(!ModeSelected)
    {
        cout << "Enter E to Encrypt or D to Decrypt: " << endl;
        char resultED[MAXCHAR];                 // stores the result if to Encrypt or Decrypt
        char *presultED(nullptr);               // stores the result
        cin.getline(resultED, MAXCHAR, '\n');   
        presultED = new char((strlen(resultED)) + 1);
        strcpy(presultED, resultED);                // copy the result the char pointer variable

        if((*(presultED + 0) == 'E') || 
           (*(presultED + 0) == 'e'))                       // The user wants Encrypt
        {
            cout << endl << "Encrypt Mode is Selected" << endl;
            Mode = ENCRYPT;
            ModeSelected = true;
        }
        else if ((*(presultED + 0) == 'D') || 
                 (*(presultED + 0) == 'd'))             // The user wants Decrypt
        {
            cout << endl << "Decrypt Mode is Selected" << endl;
            Mode = DECRYPT;
            ModeSelected = true;
        }
        else
        {
            // Input is invalid
            cout << endl << "Input is invalid" << endl;
        }
        // clean up
        if(presultED)                           // If not null then delete it
        {
            // Garbage collection
            // Contact Stack Overflow
                 delete[] presultED;
                 presultED = nullptr;
        }
    }

您会看到代码的// clean up部分正是这本书告诉我如何释放内存的。我也有点了解这背后的计算机科学。现在请告诉我这个问题。谢谢你。

4

2 回答 2

1

您使用 分配presultEDnew释放它delete[],这会产生未定义的行为

presultED = new char((strlen(resultED)) + 1);  //allocates one char

不一样

presultED = new char[(strlen(resultED)) + 1];  //allocates an array

可能还有其他一些错误,我一看到这个就停止阅读了:)

于 2012-08-27T21:25:10.560 回答
1

问题是您没有分配数组,char而是char通过调用删除数组delete[]

你应该分配

presultED = new char[(strlen(resultED)) + 1];

像这样,因为这会创建一个 s 数组char

如果不存在数组,则无法删除。

于 2012-08-27T21:27:51.917 回答