RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using a Good Parasite Class to Design a Self-Clearing Memory Buffer

Your C++ application doesn't have to allocate a new chunk of memory on every loop iteration. Learn how to implement a single raw memory buffer that knows how to clear itself securely.


any applications use a loop that fills a raw memory buffer with data, processes that data, and then clears that buffer before the next iteration. Standard containers such as vector<char>aren't suitable for representing such a memory buffer. This 10-Minute Solution shows a revolutionary technique for implementing a secure, automatic raw memory buffer that clears itself.

The Self-Recycling Buffer Problem

Your mobile carrier's SMS server, mail client, word processor, and database engine are instances of software applications that use a main loop (known as a message queue). They use these message queues for reading data from an input source into a local memory buffer for further processing. When the processing is done, the applications clear the raw buffer (meaning all bytes are set to binary zeros) before the next loop iteration takes place.

In these types of applications, using a standard container or a smart pointer to implement the raw memory buffer isn't a good design choice. For example, this loop works but it's very inefficient:

vector<char> client_sms_buffer(161);
for(;;) //main processing loop
  client_sms_buffer.clear();//actually deallocates memory
  client_sms_buffer.resize(161); //allocate a new buffer

Vector::clear() doesn't really clear the vector's buffer; it destroys the buffer. Consequently, after every clear() call you need to allocate a new buffer of the same size using resize(). This is as silly as buying a new car every time the gas tank gets empty!

Instead of deallocating and allocating a new buffer, you can use quick and dirty workarounds like this one for clearing the same buffer:

  for(auto it=client_sms_buffer.begin(),
      it < client_sms_buffer.end(), 
         *it=[0]; //zero every byte in the buffer

However, this is tedious and inefficient because the for-loop clears every byte individually.

As you can see, STL containers are a bad choice for representing a self-recycling memory buffer.

How do I avoid allocating a new chunk of memory on every loop iteration?

Using the "good parasite class" idiom, implement a single raw memory buffer that knows how to clear itself securely.

Author's Note: Click here for answers to frequently asked questions about the good parasite class.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date