0x6B6F77616C74
0x6B6F77616C74

Reputation: 2629

Unable to manually free memory from queue of arrays

#ifndef UNICODE
#define UNICODE
#endif

#include <iostream>
#include <Windows.h>
#include <queue>


using namespace std;


void addSomeContent(queue<TCHAR*> &output)
{
    TCHAR* buffer;

    for(int i=0; i < 10000; i++)
        buffer = new TCHAR[1000];

}

int main()
{       
    queue<TCHAR*> foo;

    char sign;

beginning:

    addSomeContent(foo);

    while (!foo.empty())
    {
        delete [] foo.front();
        foo.pop();
    }

    wcout<<TEXT("Press y to repeat\n");
    cin>>sign;
    if(sign == 'y' || sign == 'Y') goto beginning;

    return 0;
}

Each iteration of this program uses up 20MB of RAM. Why is it not dispatched by this instruction?

  while (!foo.empty())
  {
    delete [] foo.front();
    foo.pop();
  }

Upvotes: 1

Views: 142

Answers (2)

Puppy
Puppy

Reputation: 146930

You're trying to delete[] memory manually. This is always bad. Use std::queue<std::vector<TCHAR>> instead. Also, goto? This is bad and you should feel bad.

If you want to add an item to the queue, you need to call a member function on it.

The following code might actually function and might not drive anyone looking at it to insanity.

void addSomeContent(std::queue<std::vector<TCHAR>> &output)
{
    for(int i=0; i < 10000; i++)
        queue.push_back(std::vector<TCHAR>(1000));
}

int recursive_main() {
    std::queue<std::vector<TCHAR>> foo;
    addSomeContent(foo);
    while(!foo.empty()) foo.pop(); // no need to delete
    std::wcout << L"Press y to repeat\n";
    char sign;
    std::cin >> sign;
    if (sign == 'y' || sign == 'Y') return recursive_main();
    return 0;
}

int main()
{       
    return recursive_main();
}

Upvotes: 0

mah
mah

Reputation: 39807

Perhaps it's because while you pass the reference of foo to addSomeContent, and addSomeContent uses it as the variable named output, addSomeContent is allocating all kinds of memory but never placing those allocations in output, so back in main, foo is empty.

At SO we want to be helpful but we really want people to try to help themselves first. This would be a simple problem for you to have spotted on your own if you have done a little debugging before you posted.

Upvotes: 2

Related Questions