alloca() variants allocate from the stack and the returned pointer goes out of scope at latest when you leave th function in which you called the alloca() function. you should use malloc(). Don't initialize anything in the constructor that can fail. If you want to put complex initializer code to the constructor then do it only if the error can be handled locally or if you can store the error into a member variable and later you check it. A better alternative to this is just initializing the member variables with default values and calling later an Init() method on the object. This has an additional benefit in contrast to the "initialization in constructor" solution: In the constructor it is discouraged to call virtual methods while in the Init() can do that easily. Instead of using __intXX Visual C++ specific fix-width integer types include <stdint.h> and use intXX_t constants, this is a portable way. Using _msize() is also rare, don't use this function. What if I pass you a pointer that isn't allocated on the heap or even if it is on the heap I pass you a pointer that points to the middle of the allocated block and not to the beginning? Instead of passing a pointer and using _msize pass in a (const void*) plus a size parameter, this is the standard when working with binary data in buffers.
#include <stdint.h>
class MyClass
{
public:
MyClass(const void* source)
: m_InputBuffer(NULL)
{
Init(source);
}
MyClass(const void* source, size_t source_size)
: m_InputBuffer(NULL)
{
Init(source, source_size);
}
bool Init(const void* source)
{
return Init(source, _msize((void*)source));
}
bool Init(const void* source, size_t source_size)
{
void* p = malloc(source_size);
if (!p)
return false;
memcpy(p, source, source_size);
m_InputBuffer = (int8_t*)p;
return true;
}
private:
int8_t* m_InputBuffer;
};