From 9f1b1cda61cbf2357f8f050cba01b8427dfb51c8 Mon Sep 17 00:00:00 2001 From: Giulio Moro Date: Tue, 9 Aug 2022 11:43:21 +0200 Subject: [PATCH] Check object alignment at runtime. May throw with pre-c++17 heap allocation. See https://github.com/Wasted-Audio/hvcc/pull/54 --- hvcc/generators/ir2c/templates/Heavy_NAME.cpp | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/hvcc/generators/ir2c/templates/Heavy_NAME.cpp b/hvcc/generators/ir2c/templates/Heavy_NAME.cpp index c984c5d7..8ab437a9 100644 --- a/hvcc/generators/ir2c/templates/Heavy_NAME.cpp +++ b/hvcc/generators/ir2c/templates/Heavy_NAME.cpp @@ -52,7 +52,14 @@ extern "C" { {%- endfor %} {%- endif %} - +#ifdef __EXCEPTIONS +class my_bad_alloc : public std::bad_alloc { + virtual const char* what() const noexcept + { + return "Heavy_{{name}} object is improperly aligned. Avoid heap allocation, use operator new or use -std=c++17\n"; + } +}; +#endif // __EXCEPTIONS /* * Class Functions @@ -60,6 +67,13 @@ extern "C" { Heavy_{{name}}::Heavy_{{name}}(double sampleRate, int poolKb, int inQueueKb, int outQueueKb) : HeavyContext(sampleRate, poolKb, inQueueKb, outQueueKb) { +#ifdef __EXCEPTIONS + if(size_t(this) & size_t(alignof(Heavy_{{name}}) - 1)) + { + my_bad_alloc e; + throw(e); + } +#endif // __EXCEPTIONS {%- for x in init_list %} numBytes += {{x}} {%- endfor %}