Bug 15301

Summary: scanf family misbehaves on %m when zero characters are read
Product: glibc Reporter: Heiki Ojasild <repentinus>
Component: stdioAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED INVALID    
Severity: normal CC: bugdal, neleai, ondra, repentinus
Priority: P2 Flags: fweimer: security-
Version: 2.17   
Target Milestone: ---   
Host: Target:
Build: Last reconfirmed:
Attachments: Testcase demonstrating the problem (identical to the one on IdeOne)
Another test case

Description Heiki Ojasild 2013-03-24 17:22:06 UTC
Demonstration at <http://ideone.com/1l4qWb> (11 lines). After the sscanf call b should point to otherwise empty null-terminated string (e.g., ""). However, as can be seen from the example, b becomes a null pointer.

The POSIX specification states: "The %c , %s , and %[ conversion specifiers shall accept an optional assignment-allocation character 'm' , which shall cause a memory buffer to be allocated to hold the string converted including a terminating null character. […] The system shall allocate a buffer as if malloc() had been called. […] If there is insufficient memory to allocate a buffer, the function shall set errno to [ENOMEM] and a conversion error shall result. If the function returns EOF, any memory successfully allocated for parameters using assignment-allocation character 'm' by this call shall be freed before the function returns." <http://pubs.opengroup.org/onlinepubs/9699919799/>

In the example case there is neither insufficient memory nor is EOF returned. Thus, b should point to "", and should not be null.
Comment 1 Heiki Ojasild 2013-03-24 17:34:56 UTC
Created attachment 6945 [details]
Testcase demonstrating the problem (identical to the one on IdeOne)
Comment 2 Heiki Ojasild 2013-03-25 01:47:50 UTC
Created attachment 6946 [details]
Another test case

It is also possible to adopt the view that since non-empty sequences do not math %[, "" should not be put into the pointer. However, in that case there is no reason to alter the value of the pointer, which glibc does as demonstrated in the attached testcase (also at <http://ideone.com/Vv3Opu>).
Comment 3 OndrejBilka 2013-05-09 16:56:04 UTC
I looked in code and probable cause is that we call realloc(x,0) that returns NULL.

However relevant code should be refactored before this can be fixed.
Comment 4 Rich Felker 2013-11-15 20:45:45 UTC
This is not a bug. The conversion specifier results in a matching failure (because no characters were read). The return value of 0 indicates that nothing was read into the argument (in particular, no pointer should be assigned when %m is used).
Comment 5 Ondrej Bilka 2013-11-17 08:17:34 UTC
As previously said a %m[ matches only nonempty sequence.