From f913695d0d0427f7ec6b2017175329b6f858c7ae Mon Sep 17 00:00:00 2001 From: Mark Wielaard Date: Fri, 26 Apr 2024 22:07:46 +0200 Subject: [PATCH] Update memcheck description of C++ new and delete Lifted from valgrind-htdocs commit 73eaff0ad. Left out the paragraph on C23 free_sized and free_sized_aligned not being supported (they are now). --- memcheck/docs/mc-manual.xml | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/memcheck/docs/mc-manual.xml b/memcheck/docs/mc-manual.xml index da4bbce89..ea07df153 100644 --- a/memcheck/docs/mc-manual.xml +++ b/memcheck/docs/mc-manual.xml @@ -319,7 +319,21 @@ Mismatched free() / delete / delete [] ]]> In C++ it's important to deallocate memory in a -way compatible with how it was allocated. The deal is: +way compatible with how it was allocated. +Most of the time in C++ you will write code that +uses new expresions and delete +expresions +(see cppreference +new expression +and cppreference +delete expression). A new expression will +call operator new to perform the allocation and +then call the constructor (if one exists) on the object. Similarly a +delete expression will call the destructor on the object (if one +exists) and then call operator delete. The array +overloads call constructors/destructors for each object in the +array. +The deal is: If allocated with @@ -340,19 +354,26 @@ way compatible with how it was allocated. The deal is: -The worst thing is that on Linux apparently it doesn't matter if -you do mix these up, but the same program may then crash on a -different platform, Solaris for example. So it's best to fix it -properly. According to the KDE folks "it's amazing how many C++ -programmers don't know this". +Mixing types of allocators and deallocators is undefined +behaviour. That means that on some platforms you might not have any +problems, but the same program may then crash on a different platform, +Solaris for example. So it's best to fix it properly. According to +the KDE folks "it's amazing how many C++ programmers don't know +this". The reason behind the requirement is as follows. In some C++ implementations, delete[] must be used for objects allocated by new[] because the compiler stores the size of the array and the pointer-to-member to the destructor of the array's content just before the pointer actually -returned. delete doesn't account for this and will get -confused, possibly corrupting the heap. +returned. delete doesn't account for this and +will get confused, possibly corrupting the heap. Even if there is no +corruption there are likely to be resource leaks since using the wrong +delete may result in the wrong number of destructors being +called. + +C++ aligned allocations need to be freed using aligned delete +with the same alignment. -- 2.11.4.GIT