diff lib/malloca.h @ 9558:c487592d112a

Protect against integer overflow in malloca() calls.
author Bruno Haible <bruno@clisp.org>
date Mon, 31 Dec 2007 11:53:40 +0100
parents 4bbc062a8384
children 2d40c73ca3d5
line wrap: on
line diff
--- a/lib/malloca.h
+++ b/lib/malloca.h
@@ -70,9 +70,19 @@
 # define freea free
 #endif
 
-/* Maybe we should also define a variant
-    nmalloca (size_t n, size_t s) - behaves like malloca (n * s)
-   If this would be useful in your application. please speak up.  */
+/* nmalloca(N,S) is an overflow-safe variant of malloca (N * S).
+   It allocates an array of N objects, each with S bytes of memory,
+   on the stack.  S must be positive and N must be nonnegative.
+   The array must be freed using freea() before the function returns.  */
+#if 1
+/* Cf. the definition of xalloc_oversized.  */
+# define nmalloca(n, s) \
+    ((n) > (size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) \
+     ? NULL \
+     : malloca ((n) * (s)))
+#else
+extern void * nmalloca (size_t n, size_t s);
+#endif
 
 
 #ifdef __cplusplus