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

コードの// クリーンアップセクションは、本がメモリの割り当てを解除する方法を教えてくれたこととまったく同じです。また、その背後にあるコンピューターサイエンスについても少し理解しています。それでは、問題を教えてください。ありがとうございました。

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配列を削除していることですchardelete[]

割り振るべし

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

これは s の配列を作成するためですchar

アレイが存在しない場合は、アレイを削除できません。

于 2012-08-27T21:27:51.917 に答える