Sources Bugzilla – Bug 11216
fmemopen returns NULL when len=0
Last modified: 2012-04-28 03:21:41 UTC
The following program prints "(nil)" demonstrating the problem: int main (int argc, char **argv) { char buf[] = ""; FILE *in = fmemopen(buf, 0, "r"); fprintf(stderr, "%p\n", in); } As a general-purpose utility for converting arbitrary strings to streams it makes no more sense to forbid empty strings (which would simply return EOF immediately) than it does to forbid empty files or /dev/null. [However, since it doesn't make sense to have an output stream with an empty buffer, it seems reasonable to continue to return NULL for the "w"rite case.] In the meantime, as a workaround in my own applications I will wrap fmemopen to open /dev/null in this case.
(In reply to comment #0) > [However, since it doesn't make sense to have an output stream > with an empty buffer, it seems reasonable to continue to return > NULL for the "w"rite case.] It might have a sense, too: every write would fail with ENOSPC, like every write to /dev/full does.
You want an existing interface to be changed just to fit what you think is best? Regardless of the impact on existing applications? There won't be any change. The implementation is as it is. Perhaps not optimal but nobody can prove there are no applications which depend on the existing semantic.
Nowadays fmemopen is specified by POSIX 2008, and POSIX 2008 has no language that it shall or may fail if the size is 0. I think this bug should be reconsidered.
Adding Eric Blake to the CC, since he may be interested in this bug from a POSIX perspective.
I've added the following text to the fmemopen(3) man page: [[ If .I size is specified as zero, .BR fmemopen () fails with the error .BR EINVAL . .\" FIXME http://sourceware.org/bugzilla/show_bug.cgi?id=11216 It would be more consistent if this case successfully created a stream that then returned end of file on the first attempt at reading. ]]