Index: trunk/psphot/src/psphotFindDetections.c
===================================================================
--- trunk/psphot/src/psphotFindDetections.c	(revision 32348)
+++ trunk/psphot/src/psphotFindDetections.c	(revision 33761)
@@ -96,5 +96,6 @@
 
     // detect the peaks in the significance image
-    detections->peaks = psphotFindPeaks (significance, readout, recipe, threshold, NMAX);
+    int totalPeaks = 0;
+    detections->peaks = psphotFindPeaks (significance, readout, recipe, threshold, NMAX, &totalPeaks);
     psMetadataAddF32  (readout->analysis, PS_LIST_TAIL, "PEAK_THRESHOLD", PS_META_REPLACE, "Peak Detection Threshold", threshold);
     if (!detections->peaks) {
@@ -103,4 +104,11 @@
 	psFree (detections);
 	psError (PSPHOT_ERR_CONFIG, false, "failed on peak search");
+        return false;
+    }
+    // hard limit on number of peaks we will accept. (To avoid memory overload in psphotStack)
+    int maxPeaks = psMetadataLookupS32 (&status, recipe, "PEAKS_NMAX_TOTAL"); PS_ASSERT (status, NULL);
+    if (maxPeaks && (totalPeaks > maxPeaks)) {
+	psFree (detections);
+	psError (PSPHOT_ERR_DATA, true, "Too many peaks %d found PEAKS_NMAX_TOTAL: %d", totalPeaks, maxPeaks);
         return false;
     }
