--- a/lib/identify.c
+++ b/lib/identify.c
@@ -196,9 +196,7 @@ static void threshold(struct quirc *q)
 		threshold_s = THRESHOLD_S_MIN;
 
 	for (y = 0; y < q->h; y++) {
-		int row_average[q->w];
-
-		memset(row_average, 0, sizeof(row_average));
+		memset(q->row_average, 0, q->w * sizeof(int));
 
 		for (x = 0; x < q->w; x++) {
 			int w, u;
@@ -216,12 +214,12 @@ static void threshold(struct quirc *q)
 			avg_u = (avg_u * (threshold_s - 1)) /
 				threshold_s + row[u];
 
-			row_average[w] += avg_w;
-			row_average[u] += avg_u;
+			q->row_average[w] += avg_w;
+			q->row_average[u] += avg_u;
 		}
 
 		for (x = 0; x < q->w; x++) {
-			if (row[x] < row_average[x] *
+			if (row[x] < q->row_average[x] *
 			    (100 - THRESHOLD_T) / (200 * threshold_s))
 				row[x] = QUIRC_PIXEL_BLACK;
 			else
--- a/lib/quirc.c
+++ b/lib/quirc.c
@@ -36,34 +36,61 @@ struct quirc *quirc_new(void)
 
 void quirc_destroy(struct quirc *q)
 {
-	if (q->image)
-		free(q->image);
+	free(q->image);
 	if (sizeof(*q->image) != sizeof(*q->pixels))
 		free(q->pixels);
-
+	free(q->row_average);
 	free(q);
 }
 
 int quirc_resize(struct quirc *q, int w, int h)
 {
-	uint8_t *new_image = realloc(q->image, w * h);
+	uint8_t		*image  = NULL;
+	quirc_pixel_t	*pixels = NULL;
+	int		*row_average = NULL;
+
+	if (w < 0 || h < 0)
+		goto fail;
+
+	image = calloc(w, h);
+	if (!image)
+		goto fail;
 
-	if (!new_image)
-		return -1;
+	size_t olddim = q->w * q->h;
+	size_t newdim = w * h;
+	size_t min = (olddim < newdim ? olddim : newdim);
+
+	(void)memcpy(image, q->image, min);
 
 	if (sizeof(*q->image) != sizeof(*q->pixels)) {
-		size_t new_size = w * h * sizeof(quirc_pixel_t);
-		quirc_pixel_t *new_pixels = realloc(q->pixels, new_size);
-		if (!new_pixels)
-			return -1;
-		q->pixels = new_pixels;
+		pixels = calloc(newdim, sizeof(quirc_pixel_t));
+		if (!pixels)
+			goto fail;
 	}
 
-	q->image = new_image;
+	row_average = calloc(w, sizeof(int));
+	if (!row_average)
+		goto fail;
+
 	q->w = w;
 	q->h = h;
+	free(q->image);
+	q->image = image;
+	if (sizeof(*q->image) != sizeof(*q->pixels)) {
+		free(q->pixels);
+		q->pixels = pixels;
+	}
+	free(q->row_average);
+	q->row_average = row_average;
 
 	return 0;
+	/* NOTREACHED */
+fail:
+	free(image);
+	free(pixels);
+	free(row_average);
+
+	return -1;
 }
 
 int quirc_count(const struct quirc *q)
--- a/lib/quirc_internal.h
+++ b/lib/quirc_internal.h
@@ -77,6 +77,7 @@ struct quirc_grid {
 struct quirc {
 	uint8_t			*image;
 	quirc_pixel_t		*pixels;
+	int			*row_average; /* used by threshold() */
 	int			w;
 	int			h;
 
