From 0bb7c1ccf2fef23cbe0e263614fc4050b96305ea Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Tue, 2 Jul 2024 21:08:45 +0200 Subject: alloc: minimal allocator for inspections --- dbg_alloc.cc | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 dbg_alloc.cc (limited to 'dbg_alloc.cc') diff --git a/dbg_alloc.cc b/dbg_alloc.cc new file mode 100644 index 0000000..c1b7490 --- /dev/null +++ b/dbg_alloc.cc @@ -0,0 +1,87 @@ +#if 0 +set -xe +trap "rm -f a.out" EXIT +clang++ -std=c++17 dbg_alloc.cc && ./a.out +g++ -std=c++17 dbg_alloc.cc && ./a.out +exit 0 +#endif + +#include +#include +#include + +template +class dbg_alloc { + inline static std::size_t INST_CNT = 0; + std::size_t inst = INST_CNT++; + +public: + using value_type = T; + + dbg_alloc() = default; + + template + dbg_alloc(const dbg_alloc&) { + } + + T* allocate(std::size_t size) noexcept { + assert(size > 0); + T* ptr = static_cast(std::calloc(sizeof(T), size)); + std::fprintf(stderr, "[%2zu] alloc %8zu (%p)\n", inst, size, ptr); + return ptr; + } + + void deallocate(T* ptr, std::size_t size) noexcept { + std::fprintf(stderr, "[%2zu] dealloc %8zu (%p)\n", inst, size, ptr); + std::free(ptr); + } +}; + +// -- EXAMPLE ------------------------------------------------------------------ + +#include +#include +#include +#include +#include + +int main() { + { + puts("-- std::vector"); + std::vector> o; + for (int i = 0; i < 5; ++i) { + o.push_back(i); + } + } + { + puts("-- std::set"); + std::set, dbg_alloc> o; + for (int i = 0; i < 5; ++i) { + o.insert(i); + } + } + { + puts("-- std::unordered_set"); + std::unordered_set, std::equal_to, dbg_alloc> + o; + for (int i = 0; i < 5; ++i) { + o.insert(i); + } + } + { + puts("-- std::map"); + std::map, dbg_alloc>> o; + for (int i = 0; i < 5; ++i) { + o[i] = i * 2; + } + } + { + puts("-- std::unordered_map"); + std::unordered_map, std::equal_to, + dbg_alloc>> + o; + for (int i = 0; i < 5; ++i) { + o[i] = i * 2; + } + } +} -- cgit v1.2.3