diff --git a/Numeric/Optimization/Algorithms/HagerZhang05.hsc b/Numeric/Optimization/Algorithms/HagerZhang05.hsc
--- a/Numeric/Optimization/Algorithms/HagerZhang05.hsc
+++ b/Numeric/Optimization/Algorithms/HagerZhang05.hsc
@@ -100,7 +100,7 @@
     bracket (mkCFunction cf) freeHaskellFunPtr $ \cf_ptr    ->
     bracket (mkCGradient cg) freeHaskellFunPtr $ \cg_ptr    ->
     bracket (mkCCombined cc) freeHaskellFunPtr $ \cc_ptr    ->
-    allocaArray (4*n)                          $ \work_ptr  -> do
+    allocateWorkSpace n                        $ \work_ptr  -> do
       -- Go to C land.
       poke param_ptr params
       ret <- cg_descent x_ptr (fromIntegral n)
@@ -113,6 +113,17 @@
   x' <- G.unsafeFreeze x
   return $ ret `seq` (x', ret, stats)
 
+-- | Allocates enough work space for CG_DESCENT.  If the number
+-- of dimensions is "small enough" then we allocate on the stack,
+-- otherwise we allocate via malloc.
+allocateWorkSpace :: Int -> (Ptr Double -> IO a) -> IO a
+allocateWorkSpace n
+    | size < threshold = allocaBytes size
+    | otherwise        = bracket (mallocBytes size) free
+    where
+      size = 4 * n * sizeOf (undefined :: Double)
+      threshold = 4096 -- gives room to 128 dimensions
+
 type CFunction = Ptr Double ->               CInt -> IO Double
 type CGradient = Ptr Double -> Ptr Double -> CInt -> IO ()
 type CCombined = Ptr Double -> Ptr Double -> CInt -> IO Double
@@ -240,7 +251,7 @@
 
 
 
--- | Function calculating the both the value of the objective
+-- | Function calculating both the value of the objective
 -- function @f@ and its gradient at a point @x@.
 data Combined t where
     VCombined :: G.Vector v Double
diff --git a/nonlinear-optimization.cabal b/nonlinear-optimization.cabal
--- a/nonlinear-optimization.cabal
+++ b/nonlinear-optimization.cabal
@@ -3,7 +3,7 @@
 Tested-With:         GHC
 Category:            Math
 Name:                nonlinear-optimization
-Version:             0.3
+Version:             0.3.1
 Stability:           experimental
 License:             GPL
 License-File:        LICENSE
