Ralph De Guzman
Ralph De Guzman

Reputation: 209

How to free a member of an array from memory allocation one by one

I have a code that goes like this:

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

I need to free the last member of array entered one by one. But I keep getting a breakpoint error. How should I do this?

Upvotes: 0

Views: 82

Answers (2)

Gall
Gall

Reputation: 1625

I'm sorry but it hurts my eyes...

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

If you are doing a char stack you should probably keep track of the last unsued index or better, use a stack.

Upvotes: 1

Sathish
Sathish

Reputation: 3870

Make this change and try it-

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

In this way only you can remove that last member from your array. After removing every thing delete the memory.

Upvotes: 1

Related Questions