Variable sized type allocation I have a type that receives serial data over a pipe:

struct Packet : Base { // Base is POD, too
  int foo;
  char data[];
};


In the context, where I instantiate Packet, I already know how large this particular packet will be, so I write:

size_t const size = sizeof(Packet) + dataLength;
std::auto_ptr&lt;Base&gt; p(new((void*)(new char[size])) Packet());
// note that it will be deleted via 'delete'


Is this a sensible way of doing this, or is there a more idiomatic way?
The main thing I see wrong is that you are not accounting for sizeof(foo).

The other problem is that auto_ptr&lt;&gt; will not de-allocate the memory correctly. It  calls delete X, but this is not legal as you did not allocate the memory with new. You need a custom destroy function (as you can provide to std::unique_ptr) that does the following:

Note: Original Question was:

std::auto_ptr&lt;Base&gt; p(malloc(size)) Packet());


Leading to my original answer:

// Assuming Packet*   packet = // stufff

packet-&gt;~Packet();   // Need to call destructor
free(packet);        // then free the memory allocated with malloc


Why not do this?

size_t const size = ...;
std::auto_ptr&lt;Base&gt; p = new Packet(size);


Then change packet too:

struct Packet : Base
{
  int foo;
  std::vector&lt;char&gt; data;
  Packet(size_t size): foo(0), data(size) {}
};


Edit:

Based on the comments and the updated question:

I posted the question here (to get more eyes on it): https://stackoverflow.com/q/9714359/14065

Which brought up two points:


You still can use std::auto_ptr&lt;>


The memory allocated with new char[size] must be freed by delete []
This is not supported by std::auto_ptr&lt;> though you may be able to use std::unique_ptr

Secondly the implementation is allowed to put a marker after the end of the object


A few other points need to be considered so please read the linked questiom.