最后一次删除错误[]

时间:2013-10-22 18:09:49

标签: c++ pointers delete-operator

我无法理解为什么delete[] *iopszString;出现错误, 你能帮我解决一下吗?

尝试输入:1 3 aaa

如果我省略了最后一次删除[]它一切正常但是没有意义因为 为了交换指针,我需要删除前一点。 The code

// Notepad.cpp

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Method definition
void addText(char** iopszString);

void main()
{

    // Const definition
    int const ADD    = 1;
    int const UPDATE = 2;
    int const DELETE = 3;
    int const SAVE   = 4;
    int const EXIT   = 5;

    // Variable definition
    int nUserCode;

    // Code section

    // Gets the user code
    cout << "Enter the code: " << endl;
    cin >> nUserCode;

    // + "\0" so 1 minimum!!!
    char* iopszString = new char[1];
    iopszString = "";

    // Runs until the exit code
    while (nUserCode != EXIT)
    {
        // Checks the exit code
        switch (nUserCode)
        {
            case ADD:
            {
                addText(&iopszString);
                cout << iopszString << endl;
                break;
            }
            case UPDATE:
            {

                break;
            }
            case DELETE:
            {

                break;
            }
            case SAVE:
            {

                break;
            }
            default:
            {
                cout << "Wrong code, try again" << endl;

                break;
            }
        }

        // Gets the user code
        cout << "Enter the code: " << endl;
        cin >> nUserCode;
    }

    // Delete the string cuz heap
    delete[] iopszString;
}

void addText(char** iopszString)
{
    // Variables definition
    int  nAddLength;

    // Code section

    // Gets the new length
    cout << "Enter the length of the added string: " << endl;
    cin >> nAddLength;

    // Always remember - the length you want+1!!
    char* szNewString = new char[nAddLength+1];

    // Gets the new string
    cout << "Enter the new string which you want to add: " << endl;
    cin >> szNewString;

    // Creating a new string (result)
    char* szResult = new char[nAddLength+1+strlen(*iopszString)];

    // Copies the old string to the new
    strcpy(szResult, *iopszString);
    strcat(szResult, szNewString);

    // Deletes the new string cuz we already copied
    delete[] szNewString;

    // Exchange pointers 
    //strcpy(*iopszString, szResult); <--- never

    // The problem!
    delete[] *iopszString;

    // Exchange pointer 
    *iopszString = szResult;
}

1 个答案:

答案 0 :(得分:6)

错误在以下两行:

char* iopszString = new char[1];
iopszString = "";

您正在使用new分配新内存,并将其位置存储在指针iopszString中。然后,您将字符串文字""的位置分配给该指针,因此指针本身的值会发生变化。它现在指向其他地方,指向您未使用new分配并且您不拥有的内存位置。因此,您丢失了所分配内存的指针(内存泄漏),当您在指向delete[]位置的指针上调用""时,它会崩溃(因为您无法释放任何{{1}的内容您尚未使用delete[]分配。

你可能想写:

new

这只会设置您分配给char* iopszString = new char[1]; iopszString[0] = '\0'; 的第一个char的值,从而将其转换为有效的,空的,以零结尾的字符串。