ucx/mempool.c

changeset 157
0b33b9396851
parent 152
62921b370c60
--- a/ucx/mempool.c	Mon Feb 04 14:46:11 2019 +0100
+++ b/ucx/mempool.c	Mon Feb 04 17:49:50 2019 +0100
@@ -1,7 +1,7 @@
 /*
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
  *
- * Copyright 2016 Olaf Wintermann. All rights reserved.
+ * Copyright 2017 Mike Becker, Olaf Wintermann All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
@@ -26,6 +26,8 @@
  * POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "ucx/mempool.h"
+
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
@@ -34,8 +36,6 @@
 #endif
 #include <inttypes.h>
 
-#include "mempool.h"
-
 /** Capsule for destructible memory chunks. */
 typedef struct {
     /** The destructor for the memory chunk. */
@@ -56,18 +56,26 @@
     void           *ptr;
 } ucx_regdestr;
 
-UCX_EXTERN void ucx_mempool_shared_destr(void* ptr) {
+#ifdef __cplusplus
+extern "C"
+#endif
+void ucx_mempool_shared_destr(void* ptr) {
     ucx_regdestr *rd = (ucx_regdestr*)ptr;
     rd->destructor(rd->ptr);
 }
 
 UcxMempool *ucx_mempool_new(size_t n) {
+    size_t poolsz;
+    if(ucx_szmul(n, sizeof(void*), &poolsz)) {
+        return NULL;
+    }
+    
     UcxMempool *pool = (UcxMempool*)malloc(sizeof(UcxMempool));
     if (!pool) {
         return NULL;
     }
     
-    pool->data = (void**) malloc(n * sizeof(void*));
+    pool->data = (void**) malloc(poolsz);
     if (pool->data == NULL) {
         free(pool);
         return NULL;
@@ -97,7 +105,12 @@
         return 1;
     }
     
-    void **data = (void**) realloc(pool->data, newcap*sizeof(void*));
+    size_t newcapsz;
+    if(ucx_szmul(newcap, sizeof(void*), &newcapsz)) {
+        return 1;
+    }
+    
+    void **data = (void**) realloc(pool->data, newcapsz);
     if (data) {
         pool->data = data; 
         pool->size = newcap;
@@ -108,6 +121,10 @@
 }
 
 void *ucx_mempool_malloc(UcxMempool *pool, size_t n) {
+    if(((size_t)-1) - sizeof(ucx_destructor) < n) {
+        return NULL;
+    }
+    
     if (pool->ndata >= pool->size) {
         size_t newcap = pool->size*2;
         if (newcap < pool->size || ucx_mempool_chcap(pool, newcap)) {
@@ -129,7 +146,12 @@
 }
 
 void *ucx_mempool_calloc(UcxMempool *pool, size_t nelem, size_t elsize) {
-    void *ptr = ucx_mempool_malloc(pool, nelem*elsize);
+    size_t msz;
+    if(ucx_szmul(nelem, elsize, &msz)) {
+        return NULL;
+    }
+    
+    void *ptr = ucx_mempool_malloc(pool, msz);
     if (!ptr) {
         return NULL;
     }
@@ -138,6 +160,10 @@
 }
 
 void *ucx_mempool_realloc(UcxMempool *pool, void *ptr, size_t n) {
+    if(((size_t)-1) - sizeof(ucx_destructor) < n) {
+        return NULL;
+    }
+    
     char *mem = ((char*)ptr) - sizeof(ucx_destructor);
     char *newm = (char*) realloc(mem, n + sizeof(ucx_destructor));
     if (!newm) {

mercurial