From db9a58f48c6eae16fbfcd89d59b09e123dbed54f Mon Sep 17 00:00:00 2001 From: "Luke T. Shumaker" Date: Tue, 15 Apr 2025 15:58:31 -0600 Subject: libmisc: Add alloc.h to help detect wrong alloc sizes Lo and behold, there was a mistake in chan.c. --- libmisc/include/libmisc/alloc.h | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 libmisc/include/libmisc/alloc.h (limited to 'libmisc/include') diff --git a/libmisc/include/libmisc/alloc.h b/libmisc/include/libmisc/alloc.h new file mode 100644 index 0000000..afddbce --- /dev/null +++ b/libmisc/include/libmisc/alloc.h @@ -0,0 +1,26 @@ +/* libmisc/alloc.h - Type-safe wrappers around alloca and malloc + * + * Copyright (C) 2025 Luke T. Shumaker + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +#ifndef _LIBMISC_ALLOC_H_ +#define _LIBMISC_ALLOC_H_ + +#include /* for alloca() */ +#include /* for calloc(), free() */ +#include /* for memset() */ + +#define stack_alloc(N, TYP) ({ \ + size_t _size; \ + TYP *_ret = NULL; \ + if (!__builtin_mul_overflow(N, sizeof(TYP), &_size)) { \ + _ret = alloca(_size); \ + memset(_ret, 0, _size); \ + } \ + _ret; \ +}) + +#define heap_alloc(N, TYP) ((TYP *)calloc(N, sizeof(TYP))) + +#endif /* _LIBMISC_ALLOC_H_ */ -- cgit v1.2.3-2-g168b