如何从内存分配中逐个释放数组成员

时间:2014-07-24 07:25:05

标签: c++ malloc free

我有一个代码如下:

void push(char *buffer, char entry, int length)
{
    buffer[length] = entry;
}
void main(void)
{
    char * buffer = new char;
    int length, x;


    cout << "How many: ";
    cin >> length;

    x = length;

    buffer = (char*)malloc(length + 1);

    for (int i = 0; i < length; i++)
    {
        char entry;
        cout << "Input: ";
        cin >> entry;
        push(buffer, entry, i);
    }

    for (int i = length-1; i >= 0; i--)
    {
        free(&buffer[i]);
        cout << "Success in Removing: " << buffer[i] << endl;
    }
}

我需要释放逐个输入的最后一个数组成员。但我不断收到断点错误。我该怎么做?

2 个答案:

答案 0 :(得分:1)

进行此更改并尝试 -

for (int i = length-1; i >= 0; i--)
{
    buffer[i]='\0'; // you can't free one memory location in array of memory
    cout << "Success in Removing: " << buffer[i] << endl;
}

这样只有你可以从数组中删除最后一个成员。删除所有内容delete之后。

答案 1 :(得分:1)

抱歉,但它伤害了我的眼睛......

void push(char *buffer, char entry, int length)
{
    buffer[length] = entry;
}
void main(void)
{
    char * buffer; // Nothing to do here
    int length, x;


    cout << "How many: ";
    cin >> length;

    x = length;

    // buffer = (char*)malloc(length);
    // Better
    buffer = new char[length];

    for (int i = 0; i < length; i++)
    {
        char entry;
        cout << "Input: ";
        cin >> entry;
        push(buffer, entry, i);
    }

    for (int i = length-1; i >= 0; i--)
    {
        buffer[i] = '\0'; // I assume this is some sort of char stack displayable as a string...
        cout << "Success in Removing: " << buffer[i] << endl;
    }

    delete[] buffer;
}

如果你正在做一个char堆栈,你应该跟踪最后一个未使用的索引,使用堆栈。