After an evaluation, GNOME has moved from Bugzilla to GitLab. Learn more about GitLab.
No new issues can be reported in GNOME Bugzilla anymore.
To report an issue in a GNOME project, go to GNOME GitLab.
Do not go to GNOME Gitlab for: Bluefish, Doxygen, GnuCash, GStreamer, java-gnome, LDTP, NetworkManager, Tomboy.
Bug 165954 - get_contents_stdio's initial "str"
get_contents_stdio's initial "str"
Status: RESOLVED FIXED
Product: glib
Classification: Platform
Component: general
2.6.x
Other All
: Normal minor
: ---
Assigned To: gtkdev
gtkdev
Depends on:
Blocks:
 
 
Reported: 2005-02-01 18:11 UTC by Morten Welinder
Modified: 2011-02-18 16:14 UTC
See Also:
GNOME target: ---
GNOME version: ---


Attachments
delay malloc until after the first read (2.96 KB, patch)
2005-02-05 17:11 UTC, Sven Neumann
accepted-commit_now Details | Review

Description Morten Welinder 2005-02-01 18:11:44 UTC
get_contents_stdio should wait until after the first fread before allocating
"str".  That way, any file less than the buffer size can be allocated precisely
without the need for a realloc.
Comment 1 Sven Neumann 2005-02-05 16:35:35 UTC
Without the need for several reallocs. It takes 5 reallocs to enlarge str to the
size of the read buffer. If the first memory allocation would be delayed until
after the read, we could save these reallocs for most files.
Comment 2 Sven Neumann 2005-02-05 17:11:38 UTC
Created attachment 37030 [details] [review]
delay malloc until after the first read
Comment 3 Sven Neumann 2005-02-05 17:21:23 UTC
This patch changes get_contents_stdio() so that:

 - If the first read is shorter than the size of the read buffer,
   allocate exactly the number of read bytes + 1.
 - Otherwise allocate 2048 bytes (the size of the read buffer).

The patch also adds a simple unit test for g_file_get_contents().

BTw, shouldn't the size of the read buffer be increased to 4096 bytes? On most
systems that should be a better estimate of the block size of the underlying
file system.
Comment 4 Matthias Clasen 2005-02-06 03:20:47 UTC
Looks fine to me; bumping the buffer size to 4k sounds fine too.
Comment 5 Sven Neumann 2005-03-10 12:56:42 UTC
Committed to the HEAD branch, closing as FIXED.

2005-03-10  Sven Neumann  <sven@gimp.org>

	* glib/gfileutils.c (get_contents_stdio): delay memory allocation
	until after the first read. Saves a bunch of reallocs. Also
	increased the buffer size to 4096 bytes. (bug #165954)

	* tests/file-test.c (test_get_contents): added a (very basic) test
	for g_file_get_contents().