bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [PATCH] stat: don't explicitly request file size for filenames


From: Bruno Haible
Subject: Re: [PATCH] stat: don't explicitly request file size for filenames
Date: Fri, 05 Jul 2019 04:36:57 +0200
User-agent: KMail/5.1.3 (Linux/4.4.0-151-generic; KDE/5.18.0; x86_64; ; )

Andreas Dilger wrote:
> I was worried if
> "ls" or something is saving all of the symlink targets in memory that using a
> too-large buffer size would cause excess memory to be allocated for a long 
> time.

Good point. careadlinkat.c has a "Shrink BUF before returning it." logic,
but not all similar functions in gnulib do.

As the attached test program shows, some platforms (glibc, Cygwin) have a
special optimization for a shrinking-realloc of the last malloc()ed block.
Other platforms don't have this and a shrinking-realloc moves the data
if there is a significant gain in space by doing so.

Therefore I think it would be good to add a "Shrink BUF before returning it."
logic also to
  areadlink-with-size.c
  areadlinkat-with-size.c
  etc.

Something like this:

diff --git a/lib/areadlink-with-size.c b/lib/areadlink-with-size.c
index eacad3f..364cc08 100644
--- a/lib/areadlink-with-size.c
+++ b/lib/areadlink-with-size.c
@@ -87,6 +87,13 @@ areadlink_with_size (char const *file, size_t size)
       if (link_length < buf_size)
         {
           buffer[link_length] = 0;
+          /* Shrink BUFFER before returning it.  */
+          if (link_length + 1 < buf_size)
+            {
+              char *shrinked_buffer = realloc (buffer, link_length + 1);
+              if (shrinked_buffer != NULL)
+                buffer = shrinked_buffer;
+            }
           return buffer;
         }
 

Attachment: foo.c
Description: Text Data


reply via email to

[Prev in Thread] Current Thread [Next in Thread]