0x6B6F77616C74
0x6B6F77616C74

Reputation: 2629

Deallocating function's A run-time memory inside function B

#ifndef UNICODE
#define UNICODE
#endif

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

using namespace std;

void addSomeContent(queue<TCHAR*> &s)
{
    static int counter=0;
    TCHAR* buffer = new TCHAR[250]; //Allocate memory on heap

    wsprintf(buffer,TEXT("foo%d"),counter);

    s.push(buffer);
    counter++;

    if(counter < 10)
    addSomeContent(s);

}


int main (void)
{
    queue<TCHAR*> strings; 

    addSomeContent(strings);

    while(!strings.empty()) 
    {   
        wcout<<strings.front()<<endl;
        strings.pop();
    }

    //Here I want to destroy the "buffer" from the function "addSomeContent"
    wcout<<TEXT("Memory has been cleaned!\n");

    system("pause");
    return (0);
}

If I had deleted the wide char array at the end of the function, I couldn't have processed my queue which references to it. Now, my simple program compiles and works fine, but obviously keeping a garbage in heap isn't considered as a safe programming practice.
How to delete the "buffer" just after using it last time?

Upvotes: 0

Views: 154

Answers (3)

Seth Carnegie
Seth Carnegie

Reputation: 75130

You can use a queue<unique_ptr<TCHAR[]>> to avoid memory deallocation entirely, or you can simply deallocate the memory before you remove it from the queue like so:

delete[] strings.front();
strings.pop();

Upvotes: 2

cooky451
cooky451

Reputation: 3510

If you just want to work with strings, I would consider to just use

typedef std::basic_string<TCHAR> tstring;
std::queue<tstring> strings;

Otherwise you could use

std::queue<std::unique_ptr<TCHAR[]>> strings; // notice the [], they are important!

unique_ptr is C++11, but I think it's supported by all major compilers. I would not even consider to delete[] this manually. It is very vulnerable to errors, and not exception safe.

Upvotes: 1

tuli
tuli

Reputation: 21

Agree with Seth about using unique_ptr for your queue, or you can simply call

   delete[] strings.front()

before the strings.pop()

front() should be used to ensure we clean the element we are about to pop() i.e. the oldest element in the queue rather than back(), which is the newest!

Upvotes: 2

Related Questions