Thursday, August 30, 2007

C++ Buffer-Utils

A common C++ problem: allocate some memory block, use it inside a function, and make sure the memory block is freed when exiting the function, even if an early return statement, an exception (or a segfault) or happens. Best way: Create a class, allocate the memory block in the constructor and free it automatically in the destructor. Instantiate the class locally (i.e., on the stack), problem solved. Some conversion operators to get the mem block as char*, void* etc needed ... Additionally, a small method to nullify a pointer after free'ing the allocated memory with free(). Of course, when using C++, the clean way would be to use new char[] and delete[] ... yet I don't like these ones when I work with an unspecified memory block.



#include <cstdlib>

void freeAndNull(void* &pBuffer);

class Buffer {
 int miBufferSize;
 void* mpBuffer;
 Buffer(int bufferSize) 
  : miBufferSize(bufferSize), mpBuffer(malloc(bufferSize)) { 
  // empty
 ~Buffer() {
 int bufferSize() { 
  return miBufferSize;
 operator char*() {
  return (char*)mpBuffer;

 operator void*() {
  return mpBuffer;

#endif /*BUFFERUTILS_HH_*/

#include "BufferUtils.hh"

void freeAndNull(void* &pBuffer) {
 if (pBuffer)
 pBuffer = NULL;

No comments: