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<Base> 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?
Variable sized type allocation
c++;memory management
The main thing I see wrong is that you are not accounting for sizeof(foo).The other problem is that auto_ptr<> 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<Base> p(malloc(size)) Packet());Leading to my original answer:// Assuming Packet*   packet = // stufffpacket->~Packet();   // Need to call destructorfree(packet);        // then free the memory allocated with mallocWhy not do this?size_t const size = ...;std::auto_ptr<Base> p = new Packet(size);Then change packet too:struct Packet : Base{  int foo;  std::vector<char> 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/14065Which brought up two points:You still can use std::auto_ptr<>The memory allocated with new char[size] must be freed by delete []This is not supported by std::auto_ptr<> though you may be able to use std::unique_ptrSecondly the implementation is allowed to put a marker after the end of the objectA few other points need to be considered so please read the linked questiom.