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 s.th. 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.

BufferUtils.hh

#ifndef BUFFERUTILS_HH_
#define BUFFERUTILS_HH_

#include <cstdlib>

void freeAndNull(void* &pBuffer);

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

 operator void*() {
  return mpBuffer;
 }
};

#endif /*BUFFERUTILS_HH_*/

BufferUtils.cc

#include "BufferUtils.hh"

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

No comments: