[cfe-dev] Can replacement delete[] have side-effects?

Richard Smith via cfe-dev cfe-dev at lists.llvm.org
Tue Aug 29 13:02:32 PDT 2017


On 29 Aug 2017 12:56, "Krzysztof Parzyszek via cfe-dev" <
cfe-dev at lists.llvm.org> wrote:

Other than deallocating memory, that is?

This testcase will either print nothing, or print "Failed", depending on
how much inlining takes place. The replacement delete[] operator is treated
as the usual deallocation function and is removed despite having an
observable side-effect other than deallocation of memory.

Is the testcase correct, or is this a bug in LLVM?


A replacement global (de)allocation function can have side effects. But the
C++ standard does not require a new/delete expression to actually call the
(de)allocation function, and is permitted to provide the storage in another
way instead.

For the full details, see http://eel.is/c++draft/expr.new#10

If you want to guarantee that your functions are called (eg when testing an
allocator implementation), you can call them directly ("operator
new(size)").

--- new.cc ---
#include <new>
#include <cstdlib>
#include <cstddef>
#include <iostream>

using namespace std;

static bool global = false;

void* operator new[](::size_t size) throw(bad_alloc) {
  return ::malloc(size);
}

void operator delete[](void *ptr) throw() {
  global = true;
  if (ptr != NULL)
    ::free(ptr);
}

int main(void) {
  int *p = new int[2];
  global = false;
  delete[] p;
  if (!global)
    cout << "Failed\n";
}
--------------

$ clang++ -O2 new.cc -mllvm -inline-threshold=10
$ ./a.out
Failed

$ clang++ -O2 new.cc -mllvm -inline-threshold=100
$ ./a.out


-Krzysztof



-- 
Qualcomm Innovation Center, Inc. is a member of Code Aurora Forum, hosted
by The Linux Foundation
_______________________________________________
cfe-dev mailing list
cfe-dev at lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20170829/a408362e/attachment.html>


More information about the cfe-dev mailing list