C ++内存释放序列导致错误

时间:2012-08-27 21:22:38

标签: visual-c++ memory-management

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

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

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

2 个答案:

答案 0 :(得分:1)

您使用presultED分配new并将其与delete[]一起发布,从而产生未定义的行为

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

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

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

答案 1 :(得分:1)

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

你应该分配

presultED = new char[(strlen(resultED)) + 1];
像这样,因为它会创建一个char s。

的数组

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