]> git.ipfire.org Git - thirdparty/coreutils.git/commitdiff
(initbuf): If the desired size cannot be
authorJim Meyering <jim@meyering.net>
Sat, 3 Mar 2001 18:53:44 +0000 (18:53 +0000)
committerJim Meyering <jim@meyering.net>
Sat, 3 Mar 2001 18:53:44 +0000 (18:53 +0000)
allocated, repeatedly halve it until allocation succeeds.

src/sort.c

index 952bfe8aa24c926eede652d9cd4d0dbf4529453c..d6b46f5dff7d8d7f050411ff82d6985839a5092e 100644 (file)
@@ -698,12 +698,23 @@ sort_buffer_size (FILE *const *fps, int nfps,
 static void
 initbuf (struct buffer *buf, size_t line_bytes, size_t alloc)
 {
-  /* Ensure that the line array is properly aligned.  */
-  alloc += sizeof (struct line) - alloc % sizeof (struct line);
+  /* Ensure that the line array is properly aligned.  If the desired
+     size cannot be allocated, repeatedly halve it until allocation
+     succeeds.  The smaller allocation may hurt overall performance,
+     but that's better than failing.  */
+  for (;;)
+    {
+      alloc += sizeof (struct line) - alloc % sizeof (struct line);
+      buf->buf = malloc (alloc);
+      if (buf->buf)
+       break;
+      alloc /= 2;
+      if (alloc <= line_bytes + 1)
+       xalloc_die ();
+    }
 
   buf->line_bytes = line_bytes;
   buf->alloc = alloc;
-  buf->buf = xmalloc (buf->alloc);
   buf->used = buf->left = buf->nlines = 0;
   buf->eof = 0;
 }