<p>I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array <code>new</code> thus:</p>

<pre class="lang-cpp prettyprint-override"><code>STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];
</code></pre>

<p>Later on however the memory is freed using a <code>delete</code> call:</p>

<pre class="lang-cpp prettyprint-override"><code>delete pStruct;
</code></pre>

<p>Will this mix of array <code>new[]</code> and non-array <code>delete</code> cause a memory leak or would it depend on the compiler?  Would I be better off changing this code to use <code>malloc</code> and <code>free</code> instead?</p>

[{'answer_id': 73157, 'author': 'Fire Lancer', 'author_id': 6266, 'author_profile': 'https://Stackoverflow.com/users/6266', 'pm_score': 0, 'selected': False, 'text': "<p>Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.</p>\n\n<p>Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)</p>\n\n<p>Better would be to do it correctly, as this will also correctly call any constructors and deconstructors</p>\n\n<pre><code>STRUCT* pStruct = new STRUCT;\n...\ndelete pStruct;\n</code></pre>\n"}, {'answer_id': 73163, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 5, 'selected': True, 'text': "<p>Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.</p>\n\n<p>More importantly if <code>STRUCT</code> where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.</p>\n\n<p>Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:</p>\n\n<pre><code>delete [] (BYTE*) pStruct;\n</code></pre>\n"}, {'answer_id': 73189, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 0, 'selected': False, 'text': "<p>You'd could cast back to a BYTE * and the delete:</p>\n\n<pre><code>delete[] (BYTE*)pStruct;\n</code></pre>\n"}, {'answer_id': 73201, 'author': 'slicedlime', 'author_id': 11230, 'author_profile': 'https://Stackoverflow.com/users/11230', 'pm_score': 3, 'selected': False, 'text': "<p>The behaviour of the code is undefined. You may be lucky (or not) and it may work with your compiler, but really that's not correct code. There's two problems with it:</p>\n\n<ol>\n<li>The <code>delete</code> should be an array <code>delete []</code>.</li>\n<li>The <code>delete</code> should be called on a pointer to the same type as the type allocated.</li>\n</ol>\n\n<p>So to be entirely correct, you want to be doing something like this:</p>\n\n<pre><code>delete [] (BYTE*)(pStruct);\n</code></pre>\n"}, {'answer_id': 73219, 'author': 'Serge', 'author_id': 1007, 'author_profile': 'https://Stackoverflow.com/users/1007', 'pm_score': -1, 'selected': False, 'text': '<p>Rob Walker <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73163">reply</a> is good.</p>\n\n<p>Just small addition, if you don\'t have any constructor or/and distructors, so you basically need allocate and free a chunk of raw memory, consider using free/malloc pair.</p>\n'}, {'answer_id': 73225, 'author': 'QBziZ', 'author_id': 11572, 'author_profile': 'https://Stackoverflow.com/users/11572', 'pm_score': 0, 'selected': False, 'text': "<p>It's always best to keep acquisition/release of any resource as balanced as possible.\nAlthough leaking or not is hard to say in this case. It depends on the compiler's implementation of the vector (de)allocation.</p>\n\n<pre><code>BYTE * pBytes = new BYTE [sizeof(STRUCT) + nPaddingSize];\n\nSTRUCT* pStruct = reinterpret_cast&lt; STRUCT* &gt; ( pBytes ) ;\n\n // do stuff with pStruct\n\ndelete [] pBytes ;\n</code></pre>\n"}, {'answer_id': 73233, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You\'re sort of mixing C and C++ ways of doing things.  Why allocate more than the size of a STRUCT?  Why not just "new STRUCT"?  If you must do this then it might be clearer to use malloc and free in this case, since then you or other programmers might be a little less likely to make assumptions about the types and sizes of the allocated objects.</p>\n'}, {'answer_id': 73295, 'author': 'Len Holgate', 'author_id': 7925, 'author_profile': 'https://Stackoverflow.com/users/7925', 'pm_score': 3, 'selected': False, 'text': '<p>Yes it will cause a memory leak.</p>\n\n<p>See this except from C++ Gotchas: <a href="http://www.informit.com/articles/article.aspx?p=30642" rel="nofollow noreferrer"><a href="http://www.informit.com/articles/article.aspx?p=30642" rel="nofollow noreferrer">http://www.informit.com/articles/article.aspx?p=30642</a></a> for why.</p>\n\n<p>Raymond Chen has an explanation of how vector <code>new</code> and <code>delete</code> differ from the scalar versions under the covers for the Microsoft compiler... Here: \n<a href="http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx" rel="nofollow noreferrer"><a href="http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx</a></a> </p>\n\n<p>IMHO you should fix the delete to:</p>\n\n<pre><code>delete [] pStruct;\n</code></pre>\n\n<p>rather than switching to <code>malloc</code>/<code>free</code>, if only because it\'s a simpler change to make without making mistakes ;)</p>\n\n<p>And, of course, the simpler to make change that I show above is wrong due to the casting in the original allocation, it should be </p>\n\n<pre><code>delete [] reinterpret_cast&lt;BYTE *&gt;(pStruct);\n</code></pre>\n\n<p>so, I guess it\'s probably as easy to switch to <code>malloc</code>/<code>free</code> after all ;)</p>\n'}, {'answer_id': 73332, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Len: the problem with that is that pStruct is a STRUCT*, but the memory allocated is actually a BYTE[] of some unknown size.  So delete[] pStruct will not de-allocate all of the allocated memory.</p>\n'}, {'answer_id': 73368, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 0, 'selected': False, 'text': '<p>Use operator new and delete:</p>\n\n<pre><code>struct STRUCT\n{\n  void *operator new (size_t)\n  {\n    return new char [sizeof(STRUCT) + nPaddingSize];\n  }\n\n  void operator delete (void *memory)\n  {\n    delete [] reinterpret_cast &lt;char *&gt; (memory);\n  }\n};\n\nvoid main()\n{\n  STRUCT *s = new STRUCT;\n  delete s;\n}\n</code></pre>\n'}, {'answer_id': 73420, 'author': 'ben', 'author_id': 4607, 'author_profile': 'https://Stackoverflow.com/users/4607', 'pm_score': 2, 'selected': False, 'text': '<p>The C++ standard clearly states:</p>\n\n<pre><code>delete-expression:\n             ::opt delete cast-expression\n             ::opt delete [ ] cast-expression\n</code></pre>\n\n<blockquote>\n  <p>The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void.</p>\n  \n  <p>In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object [...] If not, the behavior is undefined.</p>\n</blockquote>\n\n<p>The value of the operand in <code>delete pStruct</code> is a pointer to an array of <code>char</code>, independent of its static type (<code>STRUCT*</code>). Therefore, any discussion of memory leaks is quite pointless, because the code is ill-formed, and a C++ compiler is not required to produce a sensible executable in this case.</p>\n\n<p>It could leak memory, it could not, or it could do anything up to crashing your system. Indeed, a C++ implementation with which I tested your code aborts the program execution at the point of the delete expression.</p>\n'}, {'answer_id': 73718, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': 3, 'selected': False, 'text': "<p>I personally think you'd be better off using <code>std::vector</code> to manage your memory, so you don't need the <code>delete</code>.</p>\n\n<pre><code>std::vector&lt;BYTE&gt; backing(sizeof(STRUCT) + nPaddingSize);\nSTRUCT* pStruct = (STRUCT*)(&amp;backing[0]);\n</code></pre>\n\n<p>Once backing leaves scope, your <code>pStruct</code> is no longer valid.</p>\n\n<p>Or, you can use:</p>\n\n<pre><code>boost::scoped_array&lt;BYTE&gt; backing(new BYTE[sizeof(STRUCT) + nPaddingSize]);\nSTRUCT* pStruct = (STRUCT*)backing.get();\n</code></pre>\n\n<p>Or <code>boost::shared_array</code> if you need to move ownership around.</p>\n"}, {'answer_id': 74170, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 2, 'selected': False, 'text': '<p>If you <em>really</em> must do this sort of thing, you should probably call operator <code>new</code> directly:</p>\n\n<pre><code>STRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize);\n</code></pre>\n\n<p>I believe calling it this way avoids calling constructors/destructors.</p>\n'}, {'answer_id': 74232, 'author': 'Michael Burr', 'author_id': 12711, 'author_profile': 'https://Stackoverflow.com/users/12711', 'pm_score': 1, 'selected': False, 'text': '<p>I am currently unable to vote, but <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73201">slicedlime\'s answer</a> is preferable to <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#73163">Rob Walker\'s answer</a>, since the problem has nothing to do with allocators or whether or not the STRUCT has a destructor.</p>\n\n<p>Also note that the example code does not necessarily result in a memory leak - it\'s undefined behavior.  Pretty much anything could happen (from nothing bad to a crash far, far away).</p>\n\n<p>The example code results in undefined behavior, plain and simple.  slicedlime\'s answer is direct and to the point (with the caveat that the word \'vector\' should be changed to \'array\' since vectors are an STL thing).</p>\n\n<p>This kind of stuff is covered pretty well in the C++ FAQ (Sections 16.12, 16.13, and 16.14):</p>\n\n<p><a href="http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12" rel="nofollow noreferrer">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12</a></p>\n'}, {'answer_id': 74236, 'author': 'Richard Corden', 'author_id': 11698, 'author_profile': 'https://Stackoverflow.com/users/11698', 'pm_score': 2, 'selected': False, 'text': "<p>As highlighted in other posts:</p>\n\n<p>1) Calls to new/delete allocate memory and may call constructors/destructors (C++ '03 5.3.4/5.3.5)</p>\n\n<p>2) Mixing array/non-array versions of <code>new</code> and <code>delete</code> is undefined behaviour. (C++ '03 5.3.5/4)</p>\n\n<p>Looking at the source it appears that someone did a search and replace for <code>malloc</code> and <code>free</code> and the above is the result.  C++ does have a direct replacement for these functions, and that is to call the allocation functions for <code>new</code> and <code>delete</code> directly:</p>\n\n<pre><code>STRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize);\n// ...\npStruct-&gt;~STRUCT ();  // Call STRUCT destructor\n::operator delete (pStruct);\n</code></pre>\n\n<p>If the constructor for STRUCT should be called, then you could consider allocating the memory and then use placement <code>new</code>:</p>\n\n<pre><code>BYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize];\nSTRUCT * pStruct = new (pByteData) STRUCT ();\n// ...\npStruct-&gt;~STRUCT ();\ndelete[] pByteData;\n</code></pre>\n"}, {'answer_id': 74361, 'author': 'Eric', 'author_id': 12937, 'author_profile': 'https://Stackoverflow.com/users/12937', 'pm_score': 0, 'selected': False, 'text': '<p>I think the is no memory leak.</p>\n\n<pre><code>STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];\n</code></pre>\n\n<p>This gets translated into a memory allocation call within the operating system upon which a pointer to that memory is returned.  At the time memory is allocated, the size of <code>sizeof(STRUCT)</code> and the size of <code>nPaddingSize</code> would be known in order to fulfill any memory allocation requests against the underlying operating system.</p>\n\n<p>So the memory that is allocated is "recorded" in the operating system\'s global memory allocation tables.  Memory tables are indexed by their pointers.  So in the corresponding call to delete, all memory that was originally allocated is free.  (memory fragmentation a popular subject in this realm as well).</p>\n\n<p>You see, the C/C++ compiler is not managing memory, the underlying operating system is.</p>\n\n<p>I agree there are cleaner methods but the OP did say this was legacy code.</p>\n\n<p>In short, I don\'t see a memory leak as the accepted answer believes there to be one.</p>\n'}, {'answer_id': 74411, 'author': 'Assaf Lavie', 'author_id': 11208, 'author_profile': 'https://Stackoverflow.com/users/11208', 'pm_score': 1, 'selected': False, 'text': "<p>It's an array delete ([]) you're referring to, not a vector delete.\nA vector is std::vector, and it takes care of deletion of its elements.</p>\n"}, {'answer_id': 75945, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': -1, 'selected': False, 'text': '<p>ericmayo.myopenid.com is so wrong, that someone with enough reputation should downvote him.</p>\n\n<p>The C or C++ runtime libraries are managing the heap which is given to it in blocks by the Operating System, somewhat like you indicate, Eric.  But it <em>is</em> the responsibility of the developer to indicate to the compiler which runtime calls should be made to free memory, and possibly destruct the objects that are there.  Vector delete (aka delete[]) is necessary in this case, in order for the C++ runtime to leave the heap in a valid state.  The fact that when the PROCESS terminates, the OS is smart enough to deallocate the underlying memory blocks is not something that developers should rely on.  This would be like never calling delete at all.</p>\n'}, {'answer_id': 79620, 'author': 'Eric', 'author_id': 12937, 'author_profile': 'https://Stackoverflow.com/users/12937', 'pm_score': 0, 'selected': False, 'text': "<p>@Matt Cruikshank \nYou should pay attention and read what I wrote again because I never suggested not calling delete[] and just let the OS clean up.  And you're wrong about the C++ run-time libraries managing the heap.  If that were the case then C++ would not be portable as is today and a crashing application would never get cleaned up by the OS. (acknowledging there are OS specific run-times that make C/C++ appear non-portable).  I challenge you to find stdlib.h in the Linux sources from kernel.org.  The new keyword in C++ actually is talking to the same memory management routines as malloc.</p>\n\n<p>The C++ run-time libraries make OS system calls and it's the OS that manages the heaps.  You are partly correct in that the run-time libraries indicate when to release the memory however, they don't actually walk any heap tables directly.  In other words, the runtime you link against does not add code to your application to walk heaps to allocate or deallocate. This is the case in Windows, Linux, Solaris, AIX, etc...  It's also the reason you won't fine malloc in any Linux's kernel source nor will you find stdlib.h in Linux source.  Understand these modern operating system have virtual memory managers that complicates things a bit further.</p>\n\n<p>Ever wonder why you can make a call to malloc for 2G of RAM on a 1G box and still get back a valid memory pointer?</p>\n\n<p>Memory management on x86 processors is managed within Kernel space using three tables.  PAM (Page Allocation Table), PD (Page Directories) and PT (Page Tables).  This is at the hardware level I'm speaking of.  One of the things the OS memory manager does, not your C++ application, is to find out how much physical memory is installed on the box during boot with help of BIOS calls.  The OS also handles exceptions such as when you try to access memory your application does not have rights too. (GPF General Protection Fault).</p>\n\n<p>It may be that we are saying the same thing Matt, but I think you may be confusing the under hood functionality a bit.  I use to maintain a C/C++ compiler for a living...</p>\n"}, {'answer_id': 83972, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': 0, 'selected': False, 'text': '<p>@ericmayo - cripes.  Well, experimenting with VS2005, I can\'t get an honest leak out of scalar delete on memory that was made by vector new.  I guess the compiler behavior is "undefined" here, is about the best defense I can muster.</p>\n\n<p>You\'ve got to admit though, it\'s a really lousy practice to do what the original poster said.</p>\n\n<blockquote>\n  <p>If that were the case then C++ would\n  not be portable as is today and a\n  crashing application would never get\n  cleaned up by the OS.</p>\n</blockquote>\n\n<p>This logic doesn\'t really hold, though.  My assertion is that a compiler\'s runtime can manage the memory within the memory blocks that the OS returns to it.  This is how most virtual machines work, so your argument against portability in this case don\'t make much sense.</p>\n'}, {'answer_id': 84335, 'author': 'Eric', 'author_id': 12937, 'author_profile': 'https://Stackoverflow.com/users/12937', 'pm_score': 0, 'selected': False, 'text': '<p>@Matt Cruikshank</p>\n\n<p>"Well, experimenting with VS2005, I can\'t get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is "undefined" here, is about the best defense I can muster."</p>\n\n<p>I disagree that it\'s a compiler behavior or even a compiler issue.  The \'new\' keyword gets compiled and linked, as you pointed out, to run-time libraries.  Those run-time libraries handle the memory management calls to the OS in a OS independent consistent syntax and those run-time libraries are responsible for making malloc and new work consistently between OSes such as Linux, Windows, Solaris, AIX, etc....  This is the reason I mentioned the portability argument; an attempt to prove to you that the run-time does not actually manage memory either.  </p>\n\n<p>The OS manages memory.  </p>\n\n<p>The run-time libs interface to the OS.. On Windows, this is the virtual memory manager DLLs.  This is why stdlib.h is implemented within the GLIB-C libraries and not the Linux kernel source; if GLIB-C is used on other OSes, it\'s implementation of malloc changes to make the correct OS calls. In VS, Borland, etc.. you will never find any libraries that ship with their compilers that actually manage memory either.  You will, however, find OS specific definitions for malloc.</p>\n\n<p>Since we have the source to Linux, you can go look at how malloc is implemented there.  You will see that malloc is actually implemented in the GCC compiler which, in turn, basically makes two Linux system calls into the kernel to allocate memory.  Never, malloc itself, actually managing memory!</p>\n\n<p>And don\'t take it from me. Read the source code to Linux OS or you can see what K&amp;R say about it...  Here is a PDF link to the K&amp;R on C.</p>\n\n<p><a href="http://www.oberon2005.ru/paper/kr_c.pdf" rel="nofollow noreferrer">http://www.oberon2005.ru/paper/kr_c.pdf</a></p>\n\n<p>See near end of Page 149:\n"Calls to malloc and free may occur in any order; malloc calls\nupon the operating system to obtain more memory as necessary. These routines illustrate some of the considerations involved in writing machine-dependent code in a relatively machineindependent way, and also show a real-life application of structures, unions and typedef."</p>\n\n<p>"You\'ve got to admit though, it\'s a really lousy practice to do what the original poster said."</p>\n\n<p>Oh, I don\'t disagree there.  My point was that the original poster\'s code was not conducive of a memory leak.  That\'s all I was saying.  I didn\'t chime in on the best practice side of things.  Since the code is calling delete, the memory is getting free up.</p>\n\n<p>I agree, in your defense, if the original poster\'s code never exited or never made it to the delete call, that the code could have a memory leak but since he states that later on he sees the delete getting called.  "Later on however the memory is freed using a delete call:"</p>\n\n<p>Moreover, my reason for responding as I did was due to the OP\'s comment "variable length structures (TAPI), where the structure size will depend on variable length strings"</p>\n\n<p>That comment sounded like he was questioning the dynamic nature of the allocations against the cast being made and was consequentially wondering if that would cause a memory leak.  I was reading between the lines if you will ;).</p>\n'}, {'answer_id': 84503, 'author': 'KPexEA', 'author_id': 13676, 'author_profile': 'https://Stackoverflow.com/users/13676', 'pm_score': 0, 'selected': False, 'text': '<p>In addition to the excellent answers above, I would also like to add:</p>\n\n<p>If your code runs on linux or if you can compile it on linux then I would suggest running it through <a href="http://valgrind.org/" rel="nofollow noreferrer">Valgrind</a>. It is an excellent tool, among the myriad of useful warnings it produces it also will tell you when you allocate memory as an array and then free it as a non-array ( and vice-versa ).</p>\n'}, {'answer_id': 85021, 'author': 'Matt Cruikshank', 'author_id': 8643, 'author_profile': 'https://Stackoverflow.com/users/8643', 'pm_score': 2, 'selected': False, 'text': "<p>@eric - Thanks for the comments.  You keep saying something though, that drives me nuts:</p>\n\n<blockquote>\n  <p>Those run-time libraries handle the\n  memory management calls to the OS in a\n  OS independent consistent syntax and\n  those run-time libraries are\n  responsible for making malloc and new\n  work consistently between OSes such as\n  Linux, Windows, Solaris, AIX, etc....</p>\n</blockquote>\n\n<p>This is not true.  The compiler writer provides the implementation of the std libraries, for instance, and they are absolutely free to implement those in an OS <strong>dependent</strong> way.  They're free, for instance, to make one giant call to malloc, and then manage memory within the block however they wish.</p>\n\n<p>Compatibility is provided because the API of std, etc. is the same - not because the run-time libraries all turn around and call the exact same OS calls.</p>\n"}, {'answer_id': 108454, 'author': 'CB Bailey', 'author_id': 19563, 'author_profile': 'https://Stackoverflow.com/users/19563', 'pm_score': 2, 'selected': False, 'text': "<p>The various possible uses of the keywords new and delete seem to create a fair amount of confusion. There are always two stages to constructing dynamic objects in C++: the allocation of the raw memory and the construction of the new object in the allocated memory area. On the other side of the object lifetime there is the destruction of the object and the deallocation of the memory location where the object resided.</p>\n\n<p>Frequently these two steps are performed by a single C++ statement.</p>\n\n<pre><code>MyObject* ObjPtr = new MyObject;\n\n//...\n\ndelete MyObject;\n</code></pre>\n\n<p>Instead of the above you can use the C++ raw memory allocation functions <code>operator new</code> and <code>operator delete</code> and explicit construction (via placement <code>new</code>) and destruction to perform the equivalent steps.</p>\n\n<pre><code>void* MemoryPtr = ::operator new( sizeof(MyObject) );\nMyObject* ObjPtr = new (MemoryPtr) MyObject;\n\n// ...\n\nObjPtr-&gt;~MyObject();\n::operator delete( MemoryPtr );\n</code></pre>\n\n<p>Notice how there is no casting involved, and only one type of object is constructed in the allocated memory area. Using something like <code>new char[N]</code> as a way to allocate raw memory is technically incorrect as, logically, <code>char</code> objects are created in the newly allocated memory. I don't know of any situation where it doesn't 'just work' but it blurs the distinction between raw memory allocation and object creation so I advise against it.</p>\n\n<p>In this particular case, there is no gain to be had by separating out the two steps of <code>delete</code> but you do need to manually control the initial allocation. The above code works in the 'everything working' scenario but it will leak the raw memory in the case where the constructor of <code>MyObject</code> throws an exception. While this could be caught and solved with an exception handler at the point of allocation it is probably neater to provide a custom operator new so that the complete construction can be handled by a placement new expression.</p>\n\n<pre><code>class MyObject\n{\n    void* operator new( std::size_t rqsize, std::size_t padding )\n    {\n        return ::operator new( rqsize + padding );\n    }\n\n    // Usual (non-placement) delete\n    // We need to define this as our placement operator delete\n    // function happens to have one of the allowed signatures for\n    // a non-placement operator delete\n    void operator delete( void* p )\n    {\n        ::operator delete( p );\n    }\n\n    // Placement operator delete\n    void operator delete( void* p, std::size_t )\n    {\n        ::operator delete( p );\n    }\n};\n</code></pre>\n\n<p>There are a couple of subtle points here. We define a class placement new so that we can allocate enough memory for the class instance plus some user specifiable padding. Because we do this we need to provide a matching placement delete so that if the memory allocation succeeds but the construction fails, the allocated memory is automatically deallocated. Unfortunately, the signature for our placement delete matches one of the two allowed signatures for non-placement delete so we need to provide the other form of non-placement delete so that our real placement delete is treated as a placement delete. (We could have got around this by adding an extra dummy parameter to both our placement new and placement delete, but this would have required extra work at all the calling sites.)</p>\n\n<pre><code>// Called in one step like so:\nMyObject* ObjectPtr = new (padding) MyObject;\n</code></pre>\n\n<p>Using a single new expression we are now guaranteed that memory won't leak if any part of the new expression throws.</p>\n\n<p>At the other end of the object lifetime, because we defined operator delete (even if we hadn't, the memory for the object originally came from global operator new in any case), the following is the correct way to destroy the dynamically created object.</p>\n\n<pre><code>delete ObjectPtr;\n</code></pre>\n\n<p>Summary!</p>\n\n<ol>\n<li><p>Look no casts! <code>operator new</code> and <code>operator delete</code> deal with raw memory, placement new can construct objects in raw memory. An explicit cast from a <code>void*</code> to an object pointer is usually a sign of something logically wrong, even if it does 'just work'.</p></li>\n<li><p>We've completely ignored new[] and delete[]. These variable size objects will not work in arrays in any case.</p></li>\n<li><p>Placement new allows a new expression not to leak, the new expression still evaluates to a pointer to an object that needs destroying and memory that needs deallocating. Use of some type of smart pointer may help prevent other types of leak. On the plus side we've let a plain <code>delete</code> be the correct way to do this so most standard smart pointers will work.</p></li>\n</ol>\n"}]
['https://Stackoverflow.com/questions/73134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9236/']