1111#include <csnip/err.h>
1212#include <csnip/mem.h>
1313
14+ void * csnip_mem_alloc (size_t n , size_t size )
15+ {
16+ if (size != 0 && SIZE_MAX / size < n ) {
17+ /* Overflow */
18+ return NULL ;
19+ }
20+ return malloc (n * size );
21+ }
22+
1423/* For aligned allocation, we use posix_memalign() if possible, since
1524 * that function has the least restrictions, and best error reporting.
1625 * Failing that, we try aligned_alloc(). In the worst case, we fall
1726 * back to memalign().
1827 */
19-
2028#if defined(CSNIP_CONF__HAVE_POSIX_MEMALIGN ) \
2129 || defined(CSNIP_CONF__HAVE_ALIGNED_ALLOC ) \
2230 || defined(CSNIP_CONF__HAVE_MEMALIGN )
2331
24- void * csnip_mem_aligned_alloc (size_t nAlign , size_t nSize , int * err_ret )
32+ void * csnip_mem_aligned_alloc (size_t nAlign , size_t n , size_t size , int * err_ret )
2533{
34+ /* Compute the allocation size, taking care of possible overflow */
35+ if (size != 0 && SIZE_MAX / size < n ) {
36+ if (err_ret )
37+ * err_ret = csnip_err_RANGE ;
38+ return NULL ;
39+ }
40+ size *= n ;
41+
2642#if defined(CSNIP_CONF__HAVE_POSIX_MEMALIGN ) \
2743 || !defined(CSNIP_CONF__HAVE_ALIGNED_ALLOC )
2844 void * p_ret ;
2945#ifdef CSNIP_CONF__HAVE_POSIX_MEMALIGN
30- const int err = posix_memalign (& p_ret , nAlign , nSize );
46+ const int err = posix_memalign (& p_ret , nAlign , size );
3147#else
3248 int err = 0 ;
33- p_ret = memalign (nAlign , nSize );
49+ p_ret = memalign (nAlign , size );
3450 if (p_ret == NULL )
3551 err = errno ;
3652#endif
@@ -51,18 +67,18 @@ void* csnip_mem_aligned_alloc(size_t nAlign, size_t nSize, int* err_ret)
5167 return p_ret ;
5268#else
5369 /* use aligned_alloc() */
54- const size_t rem = nSize % nAlign ;
70+ const size_t rem = size % nAlign ;
5571 if (rem != 0 ) {
5672 const size_t toadd = nAlign - rem ;
5773 /* Check for overflow */
58- if (SIZE_MAX - toadd < nSize ) {
74+ if (SIZE_MAX - toadd < size ) {
5975 if (err_ret )
6076 * err_ret = csnip_err_RANGE ;
6177 return NULL ;
6278 }
63- nSize += toadd ;
79+ size += toadd ;
6480 }
65- void * p_ret = aligned_alloc (nAlign , nSize );
81+ void * p_ret = aligned_alloc (nAlign , size );
6682 if (p_ret == NULL && err_ret != 0 ) {
6783 if (errno == ENOMEM ) {
6884 * err_ret = csnip_err_NOMEM ;
0 commit comments