summaryrefslogtreecommitdiff
path: root/src/basic/alloc-util.h
diff options
context:
space:
mode:
authorAlexander Kuleshov <kuleshovmail@gmail.com>2016-02-16 23:51:43 +0600
committerSven Eden <yamakuzure@gmx.net>2017-06-16 10:12:57 +0200
commit5216c93baebfa4e129ea1fc6fffd2c842aaea839 (patch)
tree8a54071f9f7f9dcebd2748724521231d386cc42a /src/basic/alloc-util.h
parentda1f9afa7ea68d5bb00b7dc4b704ba15226268be (diff)
alloc-util: cleanups
This patch contains a set of little cleanups for alloc-util.h: 1. The malloc_multiply(), realloc_multiply() and memdup_multiply() functions check allocation related parameters on overflow. Let's move them to the separate size_multiply_overflow() function for simplicity, code duplication prevention and possible reuse in future. 2. use SIZE_MAX from stdlib instead of ((size_t) - 1) to be more clear. 3. The 'a'/'b' variables are renamed to 'size' and 'need' to be more clear.'
Diffstat (limited to 'src/basic/alloc-util.h')
-rw-r--r--src/basic/alloc-util.h22
1 files changed, 13 insertions, 9 deletions
diff --git a/src/basic/alloc-util.h b/src/basic/alloc-util.h
index 679ba7f39..ceeee519b 100644
--- a/src/basic/alloc-util.h
+++ b/src/basic/alloc-util.h
@@ -51,25 +51,29 @@ static inline void freep(void *p) {
#define _cleanup_free_ _cleanup_(freep)
-_malloc_ _alloc_(1, 2) static inline void *malloc_multiply(size_t a, size_t b) {
- if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
+static inline bool size_multiply_overflow(size_t size, size_t need) {
+ return _unlikely_(need != 0 && size > (SIZE_MAX / need));
+}
+
+_malloc_ _alloc_(1, 2) static inline void *malloc_multiply(size_t size, size_t need) {
+ if (size_multiply_overflow(size, need))
return NULL;
- return malloc(a * b);
+ return malloc(size * need);
}
-_alloc_(2, 3) static inline void *realloc_multiply(void *p, size_t a, size_t b) {
- if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
+_alloc_(2, 3) static inline void *realloc_multiply(void *p, size_t size, size_t need) {
+ if (size_multiply_overflow(size, need))
return NULL;
- return realloc(p, a * b);
+ return realloc(p, size * need);
}
-_alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t a, size_t b) {
- if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
+_alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t size, size_t need) {
+ if (size_multiply_overflow(size, need))
return NULL;
- return memdup(p, a * b);
+ return memdup(p, size * need);
}
void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size);